gpt4 book ai didi

c# - HttpClient 发送空 POST 数据

转载 作者:太空宇宙 更新时间:2023-11-03 20:58:33 25 4
gpt4 key购买 nike

好吧...我在 StackOverflow 中阅读了很多问题,但仍然没有得到答案,我有这个 Web API Controller :

public class ERSController : ApiController
{
[HttpGet]
public HttpResponseMessage Get()
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
resposne.Content = new StringContent("test OK");
return resposne;
}

[HttpPost]
public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
{
var resposne = new HttpResponseMessage(HttpStatusCode.OK);
//Some actions with database
resposne.Content = new StringContent("Added");
return resposne;
}

}

然后我给它写了一个小测试器:

static void Main(string[] args)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:54916/");
client.DefaultRequestHeaders.Accept.Clear();


var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");

var response = client.PostAsync("api/ERS?ID=123", content);

response.ContinueWith(p =>
{
string result = p.Result.Content.ReadAsStringAsync().Result;
Console.WriteLine(result);
});
Console.ReadKey();
}

我总是在 API 中的参数 Data 上得到 NULL

我尝试将这些行添加到测试器中:

client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));

还是NULL,我也把内容替换成:

var values = new Dictionary<string, string>();
values.Add("Data", "Data");
var content = new FormUrlEncodedContent(values);

仍然是 NULL

我尝试将请求切换为:

WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";

var values = new NameValueCollection();
values["Data"] = "hello";
var task = client.UploadValuesTaskAsync("http://localhost:54916/api/ERS?ID=123", values);
task.ContinueWith((p) =>
{
string response = Encoding.UTF8.GetString(p.Result);
Console.WriteLine(response);
});

但调试器仍然说“不!” Data 仍然是 NULL

我确实毫无问题地获得了 ID。

最佳答案

如果您想将其作为 JSON 字符串发送,您应该这样做(使用 Newtonsoft.Json ):

var serialized = JsonConvert.SerializeObject("Hello");
var content = new StringContent(serialized, Encoding.UTF8, "application/json");

您使用 FormUrlEncodedContent 几乎是正确的,您所要做的就是用空名称发送它,例如 this example :

var content = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("", "Hello")
});

var response = client.PostAsync("api/ERS?ID=123", content);

关于c# - HttpClient 发送空 POST 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47969549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com