c# - 302重定向仍尝试运行原始请求

原文 标签 c# asp.net asp.net-mvc-3 redirect http-status-code-302

302 redirect still attempting to run original request

We have a section of code which detects old URL's and performs a redirect as follows:

Response.Clear();
Response.StatusCode = 301;
Response.Status = "301 Moved Permanently";
try
{
    Response.AddHeader("Location", MyLink.GetFullPath());
} catch
{
    Response.StatusCode = 302;
    Response.Status = "302 Moved Temporarily";
    Response.AddHeader("Location", "/");
}
Response.End();

What is essentially happening is that there is an attempt at a 301 permanent redirect and if this is not successful then a "302 Moved Temporarily" is thrown to the default home page.

PROBLEM: The problem I'm encountering is as follows. If a URL entered (lets say "/product/ABC123" for example). The URL 301 redirection fails and the 302 redirect in the catch is executed, however the original URL ("/product/ABC123") is still executed in the background. When I run the website in the debugger, the 302 redirect works fine and the default home page comes up and then half a second later a supplementary page is executed and comes up with a server 500 error due to the fact that the original URL is no longer acceptable.

My question is as follows: How can I completely stop the original request and just let the 302 redirect do what it needs to do. I have tried "HttpContext.ApplicationInstance.CompleteRequest();" beneath the "Response.End()" but it did not stop the original request.

EDIT: The redirection code is being executed from the Index method of a Controller class.

Answer

If you are in a controller action, exit the action method with returning a new HttpStatusCodeResult(302).

翻译

我们有一段代码可以检测到旧的URL并执行重定向,如下所示:

Response.Clear();
Response.StatusCode = 301;
Response.Status = "301 Moved Permanently";
try
{
    Response.AddHeader("Location", MyLink.GetFullPath());
} catch
{
    Response.StatusCode = 302;
    Response.Status = "302 Moved Temporarily";
    Response.AddHeader("Location", "/");
}
Response.End();


本质上是在尝试进行301永久重定向,如果尝试不成功,则将“ 302临时移动”抛出到默认主页。

问题:我遇到的问题如下。如果输入了URL(例如,说“ / product / ABC123”)。 URL 301重定向失败,并且在catch中执行302重定向,但是原始URL(“ / product / ABC123”)仍在后台执行。当我在调试器中运行网站时,302重定向工作正常,并且出现了默认主页,然后半秒钟后,执行了一个补充页面,并由于原始URL为no而出现了服务器500错误。更长的时间可以接受。

我的问题如下:如何完全停止原始请求,仅让302重定向执行它需要做的事情。我已经尝试过“ HttpContext.ApplicationInstance.CompleteRequest();”在“ Response.End()”下面,但它没有停止原始请求。

编辑:重定向代码是从Controller类的Index方法执行的。
最佳答案
如果您正在执行控制器动作,请返回new HttpStatusCodeResult(302)退出动作方法。
相关推荐

c# - 使用属性在代码优先EF 4.1中配置TPH Discriminator列

c# - MS图表控件:格式化轴标签

c# - 通过代码刷新WPF控制

c# - 在.NET中使进程窗口可见/不可见

c# - 直接从ascx设置代码隐藏公共属性

c# - 如何确定ResourceDictionary键的顺序?

c# - guid可以是一个好的分区键吗?

c# - 我是否懒于加载这些属性?

c# - 可以使用HTTP跟踪连接吗?

c# - 我如何绑定一个简单的数组?