Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom error page when using Owin

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>
like image 821
Nitramk Avatar asked Apr 16 '15 10:04

Nitramk


1 Answers

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...

like image 63
tmoreira Avatar answered Oct 19 '22 20:10

tmoreira