Reputation: 3004
Now I need to connect to a third-party API.
The API needs to set Content-Type
to 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.
Upvotes: 2
Views: 32632
Reputation: 21726
You could refer the following sample to set the 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:
[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody]TestUserViewModel testUser)
{
return "Address A";
}
View Model:
public class TestUserViewModel
{
public string Name { get; set; }
public int Age { get; set; }
}
The result as below:
Upvotes: 8