简体   繁体   English

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

[英]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.

相关问题 如何将Content-Length,Content-Type和Last-Modified添加到HTTP响应消息头中 - How to add the Content-Length,Content-Type and Last-Modified to the HTTP Response Message Header 如何将Content-Type标头添加到.Net GET Web请求? - How to add the Content-Type header to a .Net GET web request? 如何将配置文件参数添加到 C# 中的内容类型标头? - How do I add the profile parameter to the content-type header in C#? 如何在 ASP.NET MVC 中使用 GET 请求发送 Content-Type 标头? - How can I send Content-Type header with a GET request in ASP.NET MVC? CSharp - 如何使用 HTTP 请求和 Multipart 作为 Content-Type 上传图像 - CSharp - How can I upload an image using a HTTP Request and Multipart as the Content-Type 无法设置Content-Type标头 - Can't set Content-Type header 如何设置 WebClient Content-Type Header? - How to set WebClient Content-Type Header? SOAP 消息传递需要 HTTP Content-Type 标头,但未找到 - An HTTP Content-Type header is required for SOAP messaging and none was found C#:在HTTP中使用Content-Type标头发送参数 - C#: Sending parameter with Content-Type Header in HTTP (UWP)如何在GET请求中添加不带Content-Length的Content-Type标头 - (UWP) How to add Content-Type header without Content-Length in GET request
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM