Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC : Response.Redirect(url, TRUE) does not stop request processing

Tags:

asp.net-mvc

I have a method decorated with two custom ActionFilterAttribute.

[RequiresAuthentication(Order = 1)]
[ToonAction(Order = 2)]
public ActionResult Browse(...

RequiresAuthentication attribute is coming from this article

Inside RequiresAuthentication, on it's OnActionExecuting I do:

 filterContext.HttpContext.Response.Redirect(loginUrl, true);

The line is get executed, and the arguments are all as expected. The problem is that after executing the line above, I get next attribute (ActionFilterAttribute) executed, as if redirect didn't work, it just continues executing the request, instead of simply redirecting browser.

Question: what else do I need to do to make the request handler

This is a complete method:

    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        //redirect if not authenticated
        var identity = filterContext.HttpContext.User.Identity;
        if (!identity.IsAuthenticated) {
            //use the current url for the redirect
            string redirectOnSuccess = filterContext.HttpContext.Request.Url.PathAndQuery;

            //send them off to the login page
            string redirectUrl = string.Format("?ReturnUrl={0}", redirectOnSuccess);
            string loginUrl = FormsAuthentication.LoginUrl + redirectUrl;
            filterContext.HttpContext.Response.Redirect(loginUrl, true);
            // filterContext.Result = new HttpUnauthorizedResult();
            // filterContext.HttpContext.Response.StatusCode = 0x191;
        }
    }
like image 992
THX-1138 Avatar asked Feb 02 '10 20:02

THX-1138


3 Answers

You want to set the Result on the filterContext to a RedirectResult, not do a redirect on the response.

 filterContext.Result = new RedirectResult { Url = loginUrl };

EDIT: As @Hunter Daley suggests a better mechanism would be to use the AuthorizeAttribute instead if it works for you. If you do have authentication/authorization scenarios that the AuthorizeAttribute doesn't work for, it would probably be better to derive your custom attribute from it instead of the more generic ActionFilterAttribute. In any event, the correct technique is to set the Result rather than interact with the Response directly. You might want to look at the actual AuthorizeAttribute source at http://www.codeplex.com/aspnet for ideas.

I've got a sample of custom authorization code on my blog, http://farm-fresh-code.blogspot.com, too.

like image 174
tvanfosson Avatar answered Nov 14 '22 05:11

tvanfosson


try adding the [Authorize] attribute to your Action methods instead

like image 31
hunter Avatar answered Nov 14 '22 05:11

hunter


Add

filterContext.HttpContext.Response.Clear();

at first and this at End :

filterContext.HttpContext.Response.End();

Hope this helps.

like image 2
ali62b Avatar answered Nov 14 '22 05:11

ali62b