首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Response.Redirect()将Response.RedirectLocation变为空

Response.Redirect()将Response.RedirectLocation变为空
EN

Stack Overflow用户
提问于 2012-09-14 22:01:24
回答 1查看 3.6K关注 0票数 1

我有一组Asp.Net应用程序,它们都共享一个公共HttpModule,其中包含如下代码:

代码语言:javascript
复制
public class MyModule : IHttpModule
{
    public void Dispose()
    {
    }
    public void Init( HttpApplication context )
    {
        context.Error += new EventHandler( context_Error );
    }
    private void context_Error( object sender, EventArgs e )
    {
        var lastError = HttpContext.Current.Server.GetLastError();
        doSomeStuffWithError(lastError);
        var response = HttpContext.Current.Response;
        var redirect = GetErrorRedirect(lastError);
        response.Redirect(redirect, true);
    }
}

这对我所有的应用程序都很好,除了一个。在不能正确工作的情况下,response.Redirect(.)似乎不起作用。Asp.Net不是我期望的重定向,而是重定向到它的标准错误页面。我检查了这个应用程序的配置,没有发现任何错误或与其他应用程序有很大不同。

在调查此问题时,我使用了以下一行代码修改了错误处理程序:

代码语言:javascript
复制
private void context_Error( object sender, EventArgs e )
{
    var lastError = HttpContext.Current.Server.GetLastError();
    doSomeStuffWithError(lastError);
    var response = HttpContext.Current.Response;
    var redirect = GetErrorRedirect(lastError); 
    //setting a break point here, i've verified that 'redirect' has a value in all cases
    response.Redirect(redirect, true);

    var wtf = response.RedirectLocation;
    //inspecting the value of 'wtf' here shows that it is null for one application, but equal to 'redirect' in all others.

}

当我在'wtf‘设置一个断点时,我看到了一些奇怪的行为。对于工作的应用程序,wtf包含与重定向相同的值。然而,对于我的应用程序不工作,wtf是空的。

有谁想过什么会导致wtf在这种情况下为空?

EN

回答 1

Stack Overflow用户

发布于 2012-09-19 05:54:15

您正在使用的Response.Redirect重载将调用Response.End并抛出一个ThreadAbortException。在文档中是这样说的。因此,在其他应用程序中“它工作”这一事实很有趣,因为它永远不应该在调试会话期间执行var wtf = response.RedirectLocation;,因此也不奇怪它是空的,因为它可能允许在调试期间执行该行。

此外,如果将mode设置为On或RemoteOnly用于<customErrors> 设置 In Web.config,则当然会执行默认错误页,除非在重定向之前清除错误。这是故意的。

如果需要在已经调用了的之后执行额外的代码Response.Redirect,则将false作为第二个参数传递,以避免使用HttpContext.Current.ClearError()调用Response.End清除错误

根据您的示例,我将重写您的HttpModule如下:

代码语言:javascript
复制
public class MyModule : IHttpModule
{
    public void Dispose()
    {
    }
    public void Init( HttpApplication context )
    {
        context.Error += new EventHandler( context_Error );
    }
    private void context_Error( object sender, EventArgs e )
    {
        var context = HttpContext.Current;
        var lastError = context.Server.GetLastError();

        doSomeStuffWithError(lastError);

        var response = context.Response;
        var redirect = GetErrorRedirect(lastError);

        context.ClearError();

        // pass true if execution must stop here
        response.Redirect(redirect, false);

        // do other stuff here if you pass false in redirect
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12432545

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档