简体   繁体   English

Asp.Net:Web服务抛出“线程被中止”

[英]Asp.Net : Web service throws “Thread was being aborted”

I have a web service that I call via ajax that requires the user to be logged in. in each method I want to check if the user is logged in and send a 403 code if they are not, however when I call a Response.End() I get the error "Thread was being aborted". 我有一个通过ajax调用的Web服务,该服务要求用户登录。在每种方法中,我想检查用户是否登录,如果没有登录,则发送403代码,但是当我调用Response.End()我收到错误“线程被中止”。 What should I call instead? 我该怎么称呼呢?

[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... */
    ...
}

From the MS Support issue page : MS支持问题页面

If you use the Response.End, Response.Redirect, or Server.Transfer method, a ThreadAbortException exception occurs. 如果使用Response.End,Response.Redirect或Server.Transfer方法,则会发生ThreadAbortException异常。 You can use a try-catch statement to catch this exception. 您可以使用try-catch语句来捕获此异常。

This behavior is by design. 此行为是设计使然。

To work around this problem, use one of the following methods: 要变通解决此问题,请使用下列方法之一:

  1. For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event. 对于Response.End,请调用HttpContext.Current.ApplicationInstance.CompleteRequest方法(而不是Response.End),以将代码执行绕过Application_EndRequest事件。

Since it's a WebMethod , the easiest method is to just return nothing. 由于它是WebMethod ,所以最简单的方法是不返回任何内容。 This would be equivalent behavior to ending the response for an ajax request: 这将等同于终止ajax请求的响应:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM