【问题标题】:Asp.Net : Web service throws "Thread was being aborted"Asp.Net:Web 服务抛出“线程被中止”
【发布时间】:2010-04-09 21:03:18
【问题描述】:

我有一个通过 ajax 调用的 Web 服务,它要求用户登录。在每种方法中,我想检查用户是否已登录,如果未登录,则发送 403 代码,但是当我调用Response.End() 我收到错误“线程被中止”。我应该叫什么?

[WebMethod(true)]
public string MyMethod()
{
    if(!userIsLoggedIn)
    {
            HttpContext.Current.Response.StatusCode = 403;
            HttpContext.Current.Response.End();
    }
    /* Do stuff that should not execute unless the user is logged in... */
    ...
}

【问题讨论】:

    标签: c# asp.net web-services


    【解决方案1】:

    来自MS Support issue page

    如果您使用 Response.End, Response.Redirect 或 Server.Transfer 方法,一个 ThreadAbortException 发生异常。你可以使用一个 try-catch 语句来捕捉这个 例外。

    此行为是设计使然。

    要解决此问题,请使用 以下方法:

    1. 对于 Response.End,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 方法而不是 Response.End 到 绕过代码执行到 Application_EndRequest 事件。

    【讨论】:

      【解决方案2】:

      既然是WebMethod,最简单的方法就是什么都不返回。这相当于结束 ajax 请求的响应:

      [WebMethod(true)]
      public string MyMethod()
      {
          if(!userIsLoggedIn)
          {
             HttpContext.Current.Response.StatusCode = 403;
             return null;
          }
      }
      

      【讨论】:

      • 如果我在不可为空的类型上返回 null,我会抛出错误吗?
      • @Master - 它不应该让你编译它,但你可以抛出 default(typeHere) 以确保安全。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-04-18
      • 2012-06-08
      • 1970-01-01
      • 2012-08-23
      • 1970-01-01
      • 2020-01-23
      • 1970-01-01
      相关资源
      最近更新 更多