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

Categories

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");
}
See Question&Answers more detail:os

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

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...