John John
John John

Reputation: 1

How to stop IIS 7.0 from redirecting to its own page when 403 error occurs

I am working on an asp.net mvc web application, and inside my application I have defined a custom authorization attribute , which will return 403 error if the user is not authorized as follow; and I provide two response types depending if the request is Ajax or not:-

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]

    public class CheckUserPermissionsAttribute : AuthorizeAttribute
    {

        public string Model { get; set; }
        public string Action { get; set; }

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            //code goes here .......
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {

            if (filterContext.HttpContext.Request.IsAjaxRequest())
            {
                filterContext.Result = new HttpStatusCodeResult(403, "Sorry, you do not have the required permission to perform this action.");


            }
            else
            {
                var viewResult = new ViewResult();

                viewResult.ViewName = "~/Views/Errors/_Unauthorized.cshtml";
                filterContext.HttpContext.Response.StatusCode = 403;
                filterContext.Result = viewResult;
            }


        }
    }

The problem is that my current approach works fine on my development environment (not deployed to iis), but when I deploy my application to the staging server on IIS 7 ; then all my http requests (non-ajax) that have 403 error code will be redirect to the following page,

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

instead of redirecting to the custom page which I have created ~/Views/Errors/_Unauthorized.cshtml, While if the request is Ajax it will show the jAlert box as defined inside my Ajax setup .

So I have the following two questions;

  1. So can anyone advice how I can force my IIS not to redirect to its own page when 403 error is raised , and to redirect to the ~/Views/Errors/_Unauthorized.cshtml view?

  2. Second question, why my approach worked well if the request is an Ajax request, while it fails when the request is non-Ajax ?

Thanks.

Upvotes: 3

Views: 2344

Answers (1)

Elad Lachmi
Elad Lachmi

Reputation: 10581

You can define this is the application web.config in the httpErrors element. Here is a link to the documentation: http://www.iis.net/configreference/system.webserver/httperrors

Basically you need to add this:

<httpErrors>
  <remove statusCode="403" subStatusCode="-1" />
  <error statusCode="403" path="[The path to custom page]" responseMode="ExecuteURL" />
</httpErrors>

Upvotes: 2

Related Questions