簡體   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