2012-04-30 42 views
1

我无法在AJAX请求的错误处理程序中获取正确的错误代码。每次发生错误,则返回我的StatusCode = 500。我想在我的服务明确地将它设置为HttpContext.Current.Response.StatusCode = 403;,但它仍然给了我状态= 500无法在AJAX中获取正确的状态代码错误处理程序

这是我的AJAX请求看起来像:

$.ajax({ 
      type: "POST", 
      url: "Services/someSvc.asmx/SomeMethod", 
      cache: true, 
      contentType: "application/json; charset=utf-8", 
      data:"{}", 
      dataType: "json" 
      error: ajaxFailed 
     }); 

     function ajaxFailed(xmlRequest) { 
       alert(xmlRequest.status + ' \n\r ' + //This is always 500. 
       xmlRequest.statusText + '\n\r' + 
       xmlRequest.responseText); 
     } 

我在这里失踪了什么?

+0

您是否在SomeMethod上设置了服务器端断点? –

回答

1

看起来你是几乎没有,这里有一个例子[的WebMethod],将抛出的StatusCode 403

[WebMethod] 
    public static string HelloWorld(string name) 
    { 
     HttpContext.Current.Response.Clear(); 
     HttpContext.Current.Response.StatusCode = 403; 
     return null; 
    } 

这里是调用jQuery代码。

$(document).ready(function() 
    { 
     var jsonRequest = { name: "Zach Hunter" }; 

     $.ajax({ 
      type: 'POST', 
      url: 'Demo.aspx/HelloWorld', 
      data: JSON.stringify(jsonRequest), 
      contentType: 'application/json; charset=utf-8', 
      dataType: 'json', 
      success: function (data, text) 
      { 
       $('#results').html(data.d); 
      }, 
      error: function (request, status, error) 
      { 
       $('#results').html('Status Code: ' + request.status); 
      } 
     }); 
    }); 

如果您没有返回方法签名中指定的值,则会返回状态码500。

+0

感谢您的有用答案。过了一段时间,我在Global.asax的Begin_Request中做了同样的事情,它的工作正常。虽然我返回307作为错误代码,因为我想将用户重定向到登录页面。 – Asdfg

0

根据the documentation

error(jqXHR, textStatus, errorThrown)

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and JSONP requests. This is an Ajax Event.

所以你的代码更改为更具这样的:

$.ajax({ 
    type: "POST", 
    url: "Services/someSvc.asmx/SomeMethod", 
    cache: true, 
    contentType: "application/json; charset=utf-8", 
    data:"{}", 
    dataType: "json", 
    error: ajaxFailed (jqXHR, textStatus, errorThrown) 
}); 

function ajaxFailed(jqXHR, textStatus, errorThrown) { 
    alert(errorThrown + ' \n\r ' + textStatusText);   
} 

您也可能会发现this answer provides some additional信息。

+0

我得到'未捕获的ReferenceError:jqXHR未定义' –

相关问题