Wednesday, December 10, 2014

MVC - 401 Unauthorization redirect page

Sometimes we need to redirect our pages to some specific path when 401 unauthorized error happen. But by default it will redirect to some predefined path (Ex: ../login.aspx?ReturnUrl=home/index) and it may go 404 error if not found in our project.

To customize this default redirect path, i went through many ways and finally found simple change is

<authentication mode="Forms">
      <forms timeout="60" loginUrl="~/" />

</authentication>

Note: In browser network tab we cannot see 401 (Unauthorized) error, it will show as 302 (Redirect found). To resolve this, we can customize application end request method in global.asax file like below, But it will not redirect to login page instead it will show error page.

void Application_EndRequest(object sender, EventArgs e)
{
    if (Context.Response.StatusCode == 302)
    {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }
}

No comments:

Post a Comment