Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
940 views
in Technique[技术] by (71.8m points)

asp.net mvc - MVC - Redirect inside the Constructor

I would like to know how am I able to redirect the request inside the controller constructor if I need to do it?.

For example: Inside the constructor I need to initialize an object with an dynamic value, in some cases I don't want to do it and in that case I want to redirect to some other place. At the same way the rest of the constructor will not be executed neither the "original following action".

How can I do it? Thank you

EDIT #1

Initially I used:

  public override void OnActionExecuting(ActionExecutingContext filterContext) 

There I could redirect to some other controller/action/url, but later in time, I needed to change my controller, where I initialize an variable in his constructor and have some code that really needs to redirect the request :P

I need this also because the OnActionExecuting executes AFTER the controller constructor. And in my logic, the redirect needs to be done there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Performing redirects inside the controller constructor is not a good practice because the context might not be initialized. The standard practice is to write a custom action attribute and override the OnActionExecuting method and perform the redirect inside. Example:

public class RedirectingActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        if (someConditionIsMet)
        {
            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "someOther",
                action = "someAction"
            }));
        }
    }
}

and then decorate the controller which you would like to redirect with this attribute. Be extremely careful not to decorate the controller you are redirecting to with this attribute or you are going to run into an endless loop.

So you could:

[RedirectingAction]
public class HomeController : Controller
{
    public ActionResult Index()
    {
        // This action is never going to execute if the 
        // redirecting condition is met
        return View();
    }
}

public class SomeOtherController : Controller
{
    public ActionResult SomeAction()
    {
        return View();
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...