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 请问读取环境变量文件失败是什么原因?
  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载