Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 739
pistacchio Avatar asked Aug 09 '10 10:08

pistacchio


People also ask

How do I redirect to an action in ASP NET MVC?

RedirectToAction(String, String, RouteValueDictionary) Redirects to the specified action using the action name, controller name, and route values.

How redirect a specific view from controller in MVC?

You can use the RedirectToAction() method, then the action you redirect to can return a View. The easiest way to do this is: return RedirectToAction("Index", model); Then in your Index method, return the view you want.


1 Answers

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

filterContext.Result = new RedirectResult(urlToRedirectTo);
like image 68
Łukasz W. Avatar answered Oct 10 '22 02:10

Łukasz W.