Search code examples
asp.net-mvccustom-error-pages

Custom 401 Error page in MVC without Windows Authentication


I want to show my web.config error page against 401 in ASP.NET MVC, only 404 and default error pages are working. The authentication process is my own and NOT using .net identity framework.

I am throwing new 401 exception in my controller action method.

Action:

[HttpGet]
[HandleError]
public ActionResult Delete(int id)
{
  //if (user.IsInRole(RoleType.DELETE))
  if (myOwnUserClass.IsInRole(RoleType.DELETE))
  {
      return View();
  }
  else
  {
      return new HttpStatusCodeResult(401);
      //return PartialView("_unauthorize");
  }
}   

web.config

<customErrors mode="On" defaultRedirect="~/Error/Index">
      <error statusCode="401" redirect="~/Error/Unauthorized" />
      <error statusCode="404" redirect="~/Error/NotFound"/>
    </customErrors>

And I get default 401 error page, NOT my own.

Default 401 error page similar to this

I also searched Stack Overflow for this, but those answers didn't worked for me.


Solution

  • You could try disabling the customErrors and instead use the httpErrors to handle those errors.

    <system.web>
    
      <customErrors mode="Off" />
    
      <!-- other tags removed for brevity -->
    </system.web>
    <system.webServer>
    
      <httpErrors errorMode="Custom" existingResponse="Auto">
        <clear />
        <error statusCode="401" responseMode="ExecuteURL" path="/Error/Unauthorized" />
        <error statusCode="404" responseMode="ExecuteURL" path="/Error/NotFound" />
        <error statusCode="500" responseMode="ExecuteURL" path="/Error" />
      </httpErrors>
    
      <!-- other tags removed for brevity -->
    </system.webServer>