suraj_123
suraj_123

Reputation: 159

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);

Upvotes: 0

Views: 1073

Answers (3)

XavierAM
XavierAM

Reputation: 1775

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

Upvotes: 2

Guru Stron
Guru Stron

Reputation: 141565

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

Upvotes: 1

Athanasios Kataras
Athanasios Kataras

Reputation: 26342

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.

Upvotes: 2

Related Questions