This repository has been archived by the owner on Jan 24, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Custom errors on ASP.NET
Christian Horsdal edited this page Sep 22, 2015
·
3 revisions
I wanted to be able to return custom errors from a Nancy (0.9) app hosted in ASP.NET. Turns out that's easier said than done.
Add to or change your Web.config
:
<configuration>
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="PassThrough" />
</system.webServer>
</configuration>
With this change, you should now see the default Nancy error pages. If that's all you want, excellent, but I wanted to return error messages straight from a route handler, so on we go!
Pop this extension method somewhere:
public static Response AsError(this IResponseFormatter formatter, HttpStatusCode statusCode, string message)
{
return new Response
{
StatusCode = statusCode,
ContentType = "text/plain",
Contents = stream => (new StreamWriter(stream) { AutoFlush = true }).Write(message)
};
}
Now in your route handlers you can simply
Get["/"] = parameters => Response.AsError(HttpStatusCode.NotFound, "all gone");
But you'll still see the default Nancy error page! One more thing...
In your bootstrapper, you'll need to override the default error handler with your own. Here's what I did:
protected override NancyInternalConfiguration InternalConfiguration
{
get
{
return NancyInternalConfiguration.WithOverrides(
builder => builder.StatusCodeHandlers = new List<Type>());
}
}
Then implement a NullErrorHandler
class that inherits from IErrorHandler and handles all status codes by doing exactly nothing.
Now you'll see
% curl http://localhost/
all gone
- Introduction
- Exploring the Nancy module
- Routing
- Taking a look at the DynamicDictionary
- Async
- View Engines
- Using Models
- Managing static content
- Authentication
- Lifecycle of a Nancy Application
- Bootstrapper
- Adding a custom FavIcon
- Diagnostics
- Generating a custom error page
- Localization
- SSL Behind Proxy
- Testing your application
- The cryptography helpers
- Validation
- Hosting Nancy with ASP.NET
- Hosting Nancy with WCF
- Hosting Nancy with Azure
- Hosting Nancy with Suave.IO
- Hosting Nancy with OWIN
- Hosting Nancy with Umbraco
- Hosting Nancy with Nginx on Ubuntu
- Hosting Nancy with FastCgi
- Self Hosting Nancy
- Implementing a Host
- Accessing the client certificate when using SSL
- Running Nancy on your Raspberry Pi
- Running Nancy with ASP.NET Core 3.1