如何将 Content-Type 添加到 http post 方法的标头?

Mel*_* NG 2 c# .net-core asp.net-core

现在我需要连接到第三方API。

API 需要设置Content-Typeapplication/json;charset=UTF-8.

我是这样实现的:

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 "";
            }
Run Code Online (Sandbox Code Playgroud)

但是,它会引发错误:

{"Misused header name, 'Content-Type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}
Run Code Online (Sandbox Code Playgroud)

很快我通过修改代码找到了解决方案,如下所示:

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 "";
        }
Run Code Online (Sandbox Code Playgroud)

然而,现在它报告另一个错误:

{"The format of value 'application/json;charset=\"UTF-8\"' is invalid."}
Run Code Online (Sandbox Code Playgroud)

怎么了?我该如何解决这个问题?

谢谢。

Zhi*_* Lv 8

您可以参考以下示例来设置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();
            });
Run Code Online (Sandbox Code Playgroud)

Web API 方法如下:

[HttpPost]
[Route("relativeAddress")]
public string GetAddress([FromBody]TestUserViewModel testUser)
{
    return "Address A";
}
Run Code Online (Sandbox Code Playgroud)

查看型号:

public class TestUserViewModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

结果如下:

在此输入图像描述