pistacchio
pistacchio

Reputation: 58903

ASP.NET MVC redirect from attribute

I'm trying to execute a Redirect from a method attribute. It seems to work:

public class MyAttribute: ActionFilterAttribute {
    [..]
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        [..]
        filterContext.HttpContext.Response.Redirect(urlToRedirectTo, true);
        [..]

The only problem is that the redirect is executed after the end of the method it's attached to, while i'd like the redirect to prevent the execution of the method.

Any help? Thanks

Upvotes: 18

Views: 9035

Answers (2)

Sruly
Sruly

Reputation: 10550

You need to add

filterContext.HttpContext.Response.End();

EDIT: The top is wrong the bottom is right

this should work

filterContext.Result = new RedirectResult(UrlToRedirectTo);

if you return an ActionResult then it gets executed instaed of the action itself so this should skip the action.

Upvotes: -2

Łukasz W.
Łukasz W.

Reputation: 9755

You can prevent execution of the action method by assigning an ActionResult to filterContext.Result. For example:

filterContext.Result = new RedirectResult(urlToRedirectTo);

Upvotes: 32

Related Questions