Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c# - MVC RedirectResult

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...