301 重定向的正确控制器代码
我正在从静态网站设计一个新的动态网站。我已对路线进行了排序,但我对我的操作方法有疑问。
下面是代码,但在测试和查看 Firebug 报告的标头时,如果我取出 Response.End,我假设它是 302 重定向,因为我设置了 301,但随后调用另一个操作使其成为 302,但如果我放入 Response.End 我得到 301。
我猜测添加 Response.RedirectLocation 实际上是在执行 301 重定向,因此我将返回值更改为 EmptyResult 或 null,即使该行代码永远不会执行该应用程序编译?
public ActionResult MoveOld(string id)
{
string pagename = String.Empty;
if(id == "2")
{
pagename = WebPage.SingleOrDefault(x => x.ID == 5).URL;
}
Response.StatusCode = 301;
Response.StatusDescription = "301 Moved Permanently";
Response.RedirectLocation = pagename;
Response.End();
return RedirectToAction("Details", new { pageName = pagename });
}
I am designing a new dynamic site from a static site. I have the route all sorted but I have a question on my Action method.
Below is the code but when testing and looking at the headers that Firebug reports, if I take out the Response.End it is a 302 redirect I assume because I set the 301 but then call another action which makes it a 302, but if I put in the Response.End I get a 301.
I am guessing that adding the Response.RedirectLocation is actually doing the 301 redirect so do I therefore change my return value to EmptyResult or null even though that line of code will never get executed just so the app compiles?
public ActionResult MoveOld(string id)
{
string pagename = String.Empty;
if(id == "2")
{
pagename = WebPage.SingleOrDefault(x => x.ID == 5).URL;
}
Response.StatusCode = 301;
Response.StatusDescription = "301 Moved Permanently";
Response.RedirectLocation = pagename;
Response.End();
return RedirectToAction("Details", new { pageName = pagename });
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我赞同李维的评论。这不是控制器的工作。我倾向于使用 这个 自定义301 的 ActionResult。以下是具有更多选项的修改版本。
对于 ASP.NET MVC v2+,请使用 < code>RedirectResult。
操作中的使用
I echo Levi's comments. This is not the job of the controller. I have tended to use this custom ActionResult for 301's. Below is a modified version with more options.
For ASP.NET MVC v2+, use
RedirectResult
.Usage in the action
控制器不应该负责设置 301 和重定向位置。此逻辑应封装在 ActionResult 中,并且控制器应返回该 ActionResult 的实例。请记住,Response.End() 方法不会返回(它会抛出异常);它后面的行将不会执行。
The controller should not be responsible for setting the 301 and redirect location. This logic should be encapsulated within an ActionResult, and the controller should return an instance of that ActionResult. Keep in mind that the method Response.End() does not return (it throws an exception); lines that follow it will not execute.
您可以使用 自定义 IRouteHandler 吗?在这篇博文中?
Could you use a custom IRouteHandler as noted in this blog post?
从 MVC 2.0 开始,此“RedirectResult”有一个内置的操作结果类。请参阅这篇文章了解更多信息 - MVC RedirectResult
From MVC 2.0 there is an in built action result class for this "RedirectResult". Refer this post for more info - MVC RedirectResult