为什么ASP.NET webmethod在传递查询字符串参数时返回500

时间:2011-06-19 02:39:14

标签: jquery asp.net json httpwebrequest webmethod

我有以下网络方法:

[WebMethod(true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static String requestLocalCrime(string lat, string lng)
{
    try
    {
        // Initialize the WebRequest.

        String LocalCrime = "http://policeapi2.rkh.co.uk/api/crimes-street/all-crime?lat=" + lat + "&lng=" + lng + "";

        WebRequest webRequest;
        WebResponse webResponse;

        webRequest = HttpWebRequest.Create(LocalCrime) as HttpWebRequest;
        webRequest.Method = WebRequestMethods.Http.Get;
        webRequest.ContentType = "application/json; charset=utf-8";
        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

        webRequest.Credentials = new NetworkCredential(
                ConfigurationManager.AppSettings["PoliceAPIUsername"].ToString(),
                ConfigurationManager.AppSettings["PoliceAPIPassword"].ToString());

        // Return the response. 
        webResponse = webRequest.GetResponse();

        using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), encode))

        {
            string results = reader.ReadToEnd();
            reader.Close();
            webResponse.Close();
            return results;
        }


    }
    catch(Exception e) {
        return e.Message;
    }
}

我通过jQuery调用:

 var params = {
            "lat": 50.819522,
            "lng": -0.13642
        }


$.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({ "lat": params.lat, "lng": params.lng }),
            url: "crimerequest.aspx/requestLocalCrime",
            dataType: "json",
            // success: insertCallback 
            success: function (data) {
                var result = $.parseJSON(data.d);
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);  // Returns 500
                alert(thrownError); // Internal Server Error
                return false;
            }
        });

问题是当前的LocalCrime字符串是否以500断开,但如果我将其替换为:

String LocalCrime = "http://policeapi2.rkh.co.uk/api/leicestershire/C01/crime"

然后突然没有查询字符串值就可以了。

非常感谢任何帮助。

好的我写了一个代理类,所以我现在可以调试了。 return results;确实带回了我想要的东西,但它在一个数组中,也许与它有关。我的数据看起来像这样(可能是客户端的某些内容导致数据错误):

[
{
    "category": "other-crime", 
    "id": 378815, 
    "location": {
        "latitude": "50.8188090", 
        "street": {
            "id": 379, 
            "name": "On or near Abbey Road"
        }, 
        "longitude": "-0.1196796"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "anti-social-behaviour", 
    "id": 377906, 
    "location": {
        "latitude": "50.8279907", 
        "street": {
            "id": 4721, 
            "name": "On or near Albion Street"
        }, 
        "longitude": "-0.1336384"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "anti-social-behaviour", 
    "id": 377849, 
    "location": {
        "latitude": "50.8279907", 
        "street": {
            "id": 4721, 
            "name": "On or near Albion Street"
        }, 
        "longitude": "-0.1336384"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "other-crime", 
    "id": 377801, 
    "location": {
        "latitude": "50.8279907", 
        "street": {
            "id": 4721, 
            "name": "On or near Albion Street"
        }, 
        "longitude": "-0.1336384"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "burglary", 
    "id": 377781, 
    "location": {
        "latitude": "50.8279907", 
        "street": {
            "id": 4721, 
            "name": "On or near Albion Street"
        }, 
        "longitude": "-0.1336384"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "vehicle-crime", 
    "id": 376569, 
    "location": {
        "latitude": "50.8279446", 
        "street": {
            "id": 6312, 
            "name": "On or near Alexandra Villas"
        }, 
        "longitude": "-0.1454119"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "anti-social-behaviour", 
    "id": 376525, 
    "location": {
        "latitude": "50.8279446", 
        "street": {
            "id": 6312, 
            "name": "On or near Alexandra Villas"
        }, 
        "longitude": "-0.1454119"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "anti-social-behaviour", 
    "id": 376519, 
    "location": {
        "latitude": "50.8279446", 
        "street": {
            "id": 6312, 
            "name": "On or near Alexandra Villas"
        }, 
        "longitude": "-0.1454119"
    }, 
    "context": "", 
    "month": "2011-04"
}, 
{
    "category": "anti-social-behaviour", 
    "id": 376518, 
    "location": {
        "latitude": "50.8279446", 
        "street": {
            "id": 6312, 
            "name": "On or near Alexandra Villas"
        }, 
        "longitude": "-0.1454119"
    }, 
    "context": "", 
    "month": "2011-04"
}
]

2 个答案:

答案 0 :(得分:3)

查询字符串参数需要作为JSON传递。您没有正确传递它们,因此我猜您的网络方法中latlong为空。要正确传递它们,请使用以下命令:

data: JSON.stringify({ "lat": params.lat, "lng": params.lng })

JSON.stringify方法在现代浏览器中原生实现。如果您需要维护旧版浏览器,则可能需要包含json2.js脚本,如果浏览器支持该脚本,则该脚本将使用本机方法,如果不使用其实现。

另请注意,您的Web方法返回一个纯字符串。这意味着在客户端data.d上将是一个字符串。如果你想把它作为一个对象来操作,你需要先解析它:

var result = $.parseJSON(data.d);

答案 1 :(得分:0)

如果你收到这个错误,这意味着你在某些方面在概念上做错了。理想情况下,ajax场景仅适用于中小型服务器端调用,而不是用于获取大量数据,如果你使用的是大量数据异步请求,然后你要求麻烦。所以在这种情况下,最好去实现服务器端逻辑。但是,如果你现在处于无法更改应用程序逻辑的阶段,请将此添加到web.config中:

<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="2147483644"></jsonSerialization>
</webServices>
</scripting>
</system.web.extensions>

要记住的重要一点是整数字段的最大值是2147483647,并且此限制必须保持在此值的范围内。

但现在我真的很担心,因为我需要这个应用程序可扩展以供大量使用。我完成了这项工作,但请让我知道如何改进我的练习。谢谢