繁体   English   中英

如何将 Content-Type 添加到 http 发布方法的 header 中?

[英]How can I add Content-Type to header of http post method?

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

API 需要将Content-Type设置为application/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 "";
            }

但是,它会引发错误:

{"Misused header name, 'Content-Type'. Make sure request headers are used with HttpRequestMessage, response headers with HttpResponseMessage, and content headers with HttpContent objects."}

很快我通过修改我的代码找到了一个解决方案:

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 "";
        }

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

{"The format of value 'application/json;charset=\"UTF-8\"' is invalid."}

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

谢谢你。

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

web API 方法如下:

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

查看 Model:

public class TestUserViewModel
{
    public string Name { get; set; }
    public int Age { get; set; }
}

结果如下:

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM