简体   繁体   中英

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.

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

In responses, a Content-Type header tells the client what the content type of the returned content actually is.

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.

As stated by @Athanasios, you cannot specify the Content-Type returned by the server. But, there is one thing you can try: you can tell the server that you'd like to get a JSON format response.

Set the 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. Try next:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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