2010-04-09 44 views
2

我有一个web服务,我打电话通过ajax,要求用户登录。在每个方法我想检查用户是否登录并发送403代码,如果他们不是,但是当我打电话Response.End()我得到错误“线程被中止”。我应该怎么称呼呢?Asp.Net:Web服务抛出“线程被中止”

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

回答

2

因为它是一个WebMethod,最简单的方法是只返回任何内容。这将是等效的行为来结束ajax请求的响应:

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

如果我在非空类型上返回null,我会抛出一个错误吗? – 2010-04-12 12:53:08

+0

@Master - 它不应该让你编译,但你可以抛出'default(typeHere)'来保证安全。 – 2010-04-12 12:55:48

3

MS Support issue page

如果使用到Response.End,Response.Redirect的 或Server.Transfer的 方法,一个ThreadAbortException 发生异常。您可以使用 try-catch语句来捕获此异常。

此行为是设计使然。

要解决此问题,使用一个 下列方法:

  1. 到Response.End对于,调用 HttpContext.Current.ApplicationInstance.CompleteRequest 方法,而不是要到Response.End旁路 的代码执行到 Application_EndRequest事件。
相关问题