我们如何使用 .net 代码执行 jQuery $.ajax POST

How can we perform a jQuery $.ajax POST with .net code

如何在 .net 中使用 webclient(或等效的)运行 以下代码?

function timeout_trigger() {
                $.ajax({
                    type: "POST",
                    url: "Timer.asmx/FetchTimerInfo",
                    data: "{'query':'2342600006524'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(msg) {
                      console.log(msg.d);
                    }
                });
            }

在 vb.net 中尝试,我收到 500 错误:

    Dim w = New Net.WebClient
    Dim d = New NameValueCollection

    d.Add("query", "2342600006524")

    Dim r = w.UploadValues("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo", d)

我能够使用 fiddler composer 获得预期的结果:

POST http://usage.swiftng.com/Timer.asmx/FetchTimerInfo HTTP/1.1
Host: usage.swiftng.com
Connection: keep-alive
Content-Length: 25
Pragma: no-cache
Cache-Control: no-cache
Accept: application/json, text/javascript, */*
Origin: http://usage.swiftng.com
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36
Content-Type: application/json; charset=UTF-8
Referer: http://usage.swiftng.com/Timer.aspx?2342600006524
Accept-Encoding: gzip, deflate
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6

{'query':'2342600006524'}

请指教,我哪里错了? 谢谢!

您可以使用 WebRequest class 来 post 您的数据。查看此指南以获取指南

这是一个工作示例:

Dim jsonDataBytes = Encoding.UTF8.GetBytes("{'query':'2342600006524'}")
        Dim req As WebRequest = WebRequest.Create("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo")
        req.ContentType = "application/json"
        req.Method = "POST"
        req.ContentLength = jsonDataBytes.Length


        Dim stream = req.GetRequestStream()
        stream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
        stream.Close()

        Dim response = req.GetResponse().GetResponseStream()

        Dim reader As New StreamReader(response)
        Dim res = reader.ReadToEnd()
        reader.Close()
        response.Close()

我已经解决了:

    Dim w = New Net.WebClient
    w.Headers("User-Agent") = ("Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36")
    w.Headers("Content-Type") = ("application/json; charset=UTF-8")

    Dim r = w.UploadData("http://usage.swiftng.com/Timer.asmx/FetchTimerInfo", "POST", Encoding.UTF8.GetBytes("{'query': '2342600006524'}"))
    Dim d = Encoding.UTF8.GetString(r)