Garik
Garik

Reputation: 151

How does MVC pipeline works?

Can someone clarify for me this situation:

  1. We make request for example Home\Index;
  2. In Global asax we have Application_AuthorizeRequest
  3. Application_AuthorizeRequest throw exception
  4. We have Application_Error which catch it and return new View

    IController controller = new ErrorController(); //routedata is ok controller.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

  5. Action with Error is executed (it's OK)

  6. But then MVC or ASP pipeline still try to execute Home\Index, how can I make pipeline forget about request?

As far as I understand mvc it's HttpHandler, how can I make sure that my action with error is a last step in all this chain?

Upvotes: 0

Views: 734

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

There's a problem with this setup. If you want to prevent the Index action from being called you should write a custom Authorize attribute instead of using the Authenticate_Request event:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // perform the logic you were doing in your Authenticate_Request
        // here to authorize the user. You could throw exceptions as well
        throw new Exception("ok");
    }
}

Authorization filters replace the Authenticate_Request method in ASP.NET MVC applications and that's what you should be using.

and then decorate your Index action with this attribute:

public class HomeController: Controller
{
    [MyAuthorize]
    public ActionResult Index()
    {
        ...    
    }
}

Now your Application_Error will be called, the error controller executed and the Index action never triggered, exactly as it should be.

Upvotes: 1

Related Questions