简体   繁体   English

如何在 C# 的 httpclient 中设置响应 header?

[英]How can I set response header in httpclient in C#?

I am getting response in text/html format.How can I set response header so that I get response in application/json format.我收到 text/html 格式的响应。如何设置响应 header 以便获得 application/json 格式的响应。

Code:代码:

var httpRequestMessage = new HttpRequestMessage
            {
                Method = HttpMethod.Get,
                RequestUri = builder.Uri,
                Headers = {
                    { HttpResponseHeader.ContentType.ToString(), "application/json" },
                    { "Auth", "###################################################" }
                   
                }
                
            };

            var httpResponse = await _httpClient.SendAsync(httpRequestMessage);

You don't.你没有。 Content-Type header 内容类型 header

In responses, a Content-Type header tells the client what the content type of the returned content actually is.作为响应,Content-Type header告诉客户端返回内容的实际内容类型是什么。

The server decides the content type of the response and the client uses it to handle accordingly.服务器决定响应的内容类型,客户端使用它进行相应的处理。 There is nothing you can set in your request to do that out of the box.您可以在请求中设置开箱即用的任何内容。

If you are handling the response creation, you could create a custom header to indicate the type of the response and have the server side code handle it, but that's not usually how it should be done.如果您正在处理响应创建,您可以创建一个自定义 header 来指示响应的类型并让服务器端代码处理它,但这通常不应该这样做。

As stated by @Athanasios, you cannot specify the Content-Type returned by the server.正如@Athanasios 所述,您不能指定服务器返回的 Content-Type。 But, there is one thing you can try: you can tell the server that you'd like to get a JSON format response.但是,您可以尝试一件事:您可以告诉服务器您想要获得 JSON 格式的响应。

Set the HTTP Header Accept to application/json设置 HTTP Header Accept to application/json

But, it's still up to the server in the end to decide what content will be returned但是,最终还是由服务器来决定返回什么内容

It seems that you are looking for Accept header.看来您正在寻找接受header。 Try next:接下来试试:

var httpRequestMessage = new HttpRequestMessage
        {
            Method = HttpMethod.Get,
            RequestUri = builder.Uri,
            Headers = {
                { "Accept", "application/json"},
                { "Auth", "###################################################" }                   
            }                
        };

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

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