Reputation: 1572
I'm using Owin to host WebAPI Controllers. I have Owin middleware which performs authentication and sets the following if authentication fails:
context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
When this happens I want to display a HTML page with some instructions to the user. (Like, "You need to log on.")
At the moment I'm just redirecting the user to a accessdenied.html-page, but I would prefer if the access denied was shown directly without the user being redirected (I don't want the Location field in the web browser to change).
I assume I could just generate the HTML on the fly and adding it to the response, for example by reading the HTML content from a resource.
My question is: Is it possible to do display a custom access-denied error page automatically using configuration? In "traditioinal" ASP.NET, it was possible to set up customErrors in web.config, but this does not appear to work with Owin selfhost:
<customErrors>
<error statusCode="401" redirect="~/accessdenied.html"/>
</customErrors>
Upvotes: 6
Views: 5748
Reputation: 412
owin provides you an option to redirect to your error page
context.Response.Redirect(errUrl); //context is the owinContext
You don't need to have any special RedirectResult or RedirectToAction Method.
Upvotes: -1
Reputation: 790
I came across the same issue. I tried setting StatusCode and then doing Redirect to 401 page. But Redirect changes StatusCode to 302.
I came up with solution of reading 401.html writing it to Response. It worked for me.
context.Response.StatusCode = 401;
var path = HttpContext.Current.Server.MapPath("/401.html");
var html = System.IO.File.ReadAllText(path, Encoding.UTF8);
context.Response.Write(html);
Upvotes: 0
Reputation: 124
In a previous project of mine I had to use an Owin middleware like this:
app.Use((owinContext, next) =>
{
return next().ContinueWith(x =>
{
if (owinContext.Response.StatusCode == 500 /*or 401 , etc*/)
{
//owinContext.Response.Redirect(VirtualPathUtility.ToAbsolute("~/Home/Error"));
//this should work for self-host as well
owinContext.Response.Redirect(owinContext.Request.Uri.AbsoluteUri.Replace(request.Uri.PathAndQuery, request.PathBase + "/Home/Error"));
}
});
});
you have to register the middleware before all the others.
In this case I'm redirecting the user to an Error view, but as general practice I would say it's better to have an HTML static page.
Actually I think there's an extension request for handling global exceptions. Have a look at this link...
Upvotes: 3