Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC RedirectResult

Tags:

I'm new to MVC can anyone tell me what RedirectResult is used for?

I'm was wondering what is the different between this:

public ActionResult Index() {     return new RedirectResult("http://www.google.com"); } 

and this:

public RedirectResult Index() {     return new RedirectResult("http://www.google.com"); } 
like image 361
Stacker Avatar asked Dec 08 '10 11:12

Stacker


People also ask

What is RedirectResult in MVC?

RedirectResult. RedirectResult is an ActionResult that returns a Found (302), Moved Permanently (301), Temporary Redirect (307), or Permanent Redirect (308) response with a Location header to the supplied URL. It will redirect us to the provided URL, it doesn't matter if the URL is relative or absolute.

What are action filters in MVC?

ASP.NET MVC provides Action Filters for executing filtering logic either before or after an action method is called. Action Filters are custom attributes that provide declarative means to add pre-action and post-action behavior to the controller's action methods.

How do you redirect to action?

The RedirectToAction() Method This method is used to redirect to specified action instead of rendering the HTML. In this case, the browser receives the redirect notification and make a new request for the specified action. This acts just like as Response. Redirect() in ASP.NET WebForm.


1 Answers

It is used to perform an HTTP redirect to a given url. Basically it will send the 302 status code along with the Location header in the response so that the client now issues a new HTTP request to this new location.

Usually you would use it like this instead of explicitly calling the constructor:

public ActionResult Index() {     return Redirect("http://www.google.com"); } 

As far as the difference between your two code snippets is concerned, well, it's more C# question than MVC related. In fact RedirectResult derives from ActionResult so both are valid syntaxes. Personally I prefer the first one as you could for example decide to change this redirect to return a view:

public ActionResult Index() {     return View(); } 

and if you have explicitly specified that the return type is RedirectResult instead of ActionResult you would now have to modify it to ViewResult (probably not a big deal but it's an additional step you have to do).

like image 159
Darin Dimitrov Avatar answered Dec 06 '22 18:12

Darin Dimitrov