[英]How can I add Content-Type to header of http post method?
Now I need to connect to a third-party API.现在我需要连接到第三方 API。
The API needs to set Content-Type
to application/json;charset=UTF-8
. API 需要将Content-Type
设置为application/json;charset=UTF-8
。
I achieve it like this:我是这样实现的:
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aaa.com");
request.Content = new StringContent(IP);
request.Headers.Add("Content-Type", "application/json;charset=UTF-8");
var client = clientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(5);
var response = await client.SendAsync(request);
string Content = "";
if (response.IsSuccessStatusCode)
{
Content = await response.Content.ReadAsStringAsync();
return Content;
}
else
{
return "";
}
However, it throws an error:但是,它会引发错误:
{"Misused header name, 'Content-Type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}
Soon I found a solution by modifying my code like this:很快我通过修改我的代码找到了一个解决方案:
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.aaa.com");
var RequestContent = new StringContent(IP);
RequestContent.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json;charset=UTF-8");
request.Content = RequestContent;
var client = clientFactory.CreateClient();
client.Timeout = TimeSpan.FromSeconds(5);
var response = await client.SendAsync(request);
string Content = "";
if (response.IsSuccessStatusCode)
{
Content = await response.Content.ReadAsStringAsync();
return Content;
}
else
{
return "";
}
Whereas, now it reports another error:然而,现在它报告另一个错误:
{"The format of value 'application/json;charset=\"UTF-8\"' is invalid."}
What's the matter?怎么了? And how can I solve this?我该如何解决这个问题?
Thank you.谢谢你。
You could refer the following sample to set the Content-Type:您可以参考以下示例来设置 Content-Type:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://localhost:44310/api/todo/"); //Change the Uri and request content to yours.
client.DefaultRequestHeaders
.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));//ACCEPT header
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "relativeAddress");
request.Content = new StringContent("{\"name\":\"John Doe\",\"age\":33}",
Encoding.UTF8,
"application/json");//CONTENT-TYPE header
await client.SendAsync(request)
.ContinueWith(async responseTask =>
{
Console.WriteLine("Response: {0}", responseTask.Result);
var Content = await responseTask.Result.Content.ReadAsStringAsync();
});
And the web API method like this: web API 方法如下:
[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody]TestUserViewModel testUser)
{
return "Address A";
}
View Model:查看 Model:
public class TestUserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
The result as below:结果如下:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.