tags:

views:

486

answers:

2

I am looking to set the result action from a failed IAuthorizationFilter. However I am unsure how to create an ActionResult from inside the Filter. The controller doesn't seem to be accible from inside the filter so my usual View("SomeView") isn't working. Is there a way to get the controler or else another way of creating an actionresult as it doesn't appear to be instantiable?

Doesn't work:

    [AttributeUsage(AttributeTargets.Method)]
    public sealed class RequiresAuthenticationAttribute : ActionFilterAttribute, IAuthorizationFilter
    {
    public void OnAuthorization(AuthorizationContext context)
    {
        if (!context.HttpContext.User.Identity.IsAuthenticated)
        {
            context.Result = View("User/Login");
        }
    }
}
A: 

You can instantiate the appropriate ActionResult directly, then set it on the context. For example:

public void OnAuthorization(AuthorizationContext context)
{
    if (!context.HttpContext.User.Identity.IsAuthenticated)
    {
        context.Result = new ViewResult { ViewName = "Whatever" };
    }
}
Jeremy Skinner
+2  A: 

You should look at the implementation of IAuthorizationFilter that comes with the MVC framework, AuthorizeAttribute. If you are using forms authentication, there's no need for you to set the result to User/Login. You can raise a 401 HTTP status response and ASP.NET Will redirect to the login page for you.

The one issue with setting the result to user/login is that the user's address bar is not updated, so they will be on the login page, but the URL won't match. For some people, this is not an issue. But some people want their site's URL to correspond to what the user sees in their browser.

Haacked