weixin_33690367 2015-07-14 09:53 采纳率: 0%
浏览 57

.NET中的AJAX POST

I have the below javascript AJAX request which works:

$.ajax({
    type: "POST",
    url: requestUrl,
    data: {
        var1: 'value1',
        var2: 'value2',
        var3: 'value3'
    },
    xhrFields: {
        withCredentials: true
    },
    dataType: "json",
    crossDomain: true,
    complete: function (jqXhr, textStatus) {
        if (jqXhr !== undefined && jqXhr !== null && jqXhr.statusText === "OK") {
            alert("Request Success" + jqXhr.responseText);
        } else {
            alert("Request Failed" + (jqXhr.responseText || textStatus));
        }

    }
});

I would like to do the same using .NET.

I tried the following:

string result = string.Empty;
try
{
    using (var client = new WebClient())
    {
        client.Credentials = new NetworkCredential("userName", "password");

        var values = new NameValueCollection();
        values["var1"] = "value1";
        values["var2"] = "value2";
        values["var3"] = "value3";

        var response = client.UploadValues(requestUrl, values);

        result = Encoding.Default.GetString(response);

    }
}
catch (Exception exception)
{
    Console.WriteLine("Error=" + exception.Message);
}

Console.WriteLine("result=" + result);

However I get an Internal Server Error.

How do I recreate a cross domain request? Is there a specific header to set?

WebException details:

Response: "The remote server returned an error: (500) Internal Server Error." Headers: Persistent-Auth: true Content-Length: 5143 Cache-Control: private Content-Type: text/html; charset=utf-8 Date: Tue, 14 Jul 2015 12:03:21 GMT Server: Microsoft-IIS/7.5 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET

  • 写回答

1条回答 默认 最新

  • weixin_33736649 2015-07-14 10:02
    关注

    Without seeing the error it's hard to say exactly what's going on but if you suspect this is a CORS issue then you can add these headers:

    var data = JsonConvert.SerializeObject(
        new
        {
            Prop1 = 1,
            Prop2 = "data 2"
        });
    
    using (var client = new WebClient { UseDefaultCredentials = true })
    {
        client.Headers.Add("access-control-allow-origin", "*");
        client.Headers.Add("access-control-allow-methods", "GET, POST, OPTIONS");
        client.Headers.Add("access-control-allow-headers", "Authorization, content-type, accept");
        client.Headers.Add(HttpRequestHeader.ContentType, "application/json; charset=utf-8");
        client.UploadData("your url", "POST", Encoding.UTF8.GetBytes(data));
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 单片机汇编语言相关程序
  • ¥20 家用射频美容仪技术规格
  • ¥15 大家帮我看看为什么错了
  • ¥15 unity互动琴弦抖动效果
  • ¥15 做了个的二极管反向饱和电流测量电路,但是测试达不到效果
  • ¥15 nginx无证书访问https失败
  • ¥15 树莓派启动AP热点传入数据
  • ¥15 multisim中关于74ls192n和DSWPK开关的问题(相关搜索:计数器)
  • ¥15 在误装Windows server2019 后如何利用Windows.old恢复?
  • ¥20 代码实现状态连接包过滤防火墙的设计与实现