Deepal
Deepal

Reputation: 1814

Custom Error redirection does not work in ASP.NET MVC Web.Config

In my application I have included <customerror> tag in Web.config as follows:

<customErrors mode="On">
  <error statusCode="404" redirect="/Error/404"/>
  <error statusCode="403" redirect="/Error/403"/>
  <error statusCode="500" redirect="/Error/500"/>
</customErrors>

I have created an entry in my route config such that any request with url pattern /Error/{status} goes to a specific controller action with status as a parameter.

And I have a custom ActionFilterAttribute which checks whether the user is admin and returns an HTTP 403 result if not. Following is my custom filter attribute.

public class RequireAdminAttribute: ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (!UserOperations.IsAdmin())
        {
            filterContext.Result = new Http403Result();
        }
    }
}

internal class Http403Result : ActionResult
{
    public override void ExecuteResult(ControllerContext context)
    {
        // Set the response code to 403.
        context.HttpContext.Response.StatusCode = 403;
    }
}

Now, what I need is user to be redirect to the /Error/403 page if he is not authorized. When I run my application, my applition does not redirect to the error page when 403 error occurs. If a 404 error occurs, it redirects to the given 404 error page (in most cases when 404 occurs). What is the reason for this? Can anybody give me a solution? Do I need to hardcode redirection to error page using something like RedirectToRouteResult?

Edit: In some cases redirection does not work where I explicitely used return HttpNotFound(); result as well. I would like to know whether using return HttpNotFound(); does not redirect to a custom page.

Thank you.

Upvotes: 2

Views: 2804

Answers (1)

haim770
haim770

Reputation: 49095

Try to add this to your Web.config:

<system.webServer>
  <httpErrors existingResponse="Replace" errorMode="Custom"  defaultResponseMode="Redirect">
    <remove statusCode="403"/>
    <error responseMode="ExecuteURL" statusCode="403" path="/Error/403" />
  </httpErrors>
</system.webServer>

Upvotes: 3

Related Questions