Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpClient request header customisation

Is it possible to set the request ACCEPT header of the HttpClient in .Net/Web Api to include "application/json;odata=verbose"?

I know how to set the request media type

HttpClient client = new HttpClient(handler);            
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

But how do I set the odata=verbose part? I cannot seem to find any solutions online to do that.

Do I have to use HttpWebRequest instead? Basically I need to call sharepoint 2013 rest api, and that odata=verbose part is required.

like image 876
Joshscorp Avatar asked Mar 06 '13 00:03

Joshscorp


People also ask

Can I add custom header to HTTP request?

In the Home pane, double-click HTTP Response Headers. In the HTTP Response Headers pane, click Add... in the Actions pane. In the Add Custom HTTP Response Header dialog box, set the name and value for your custom header, and then click OK.

Does HTTP allow custom headers?

If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common ...


1 Answers

MediaTypeWithQualityHeaderValue has a property called Parameters to which you can add 'odata=verbose' parameter.

Other easy way is to call MediaTypeWithQualityHeaderValue's Parse/TryParse methods to which you can supply the whole "application/json;odata=verbose" media type string.

Here is an example using Parse

using (HttpClient httpClient = new HttpClient())
{
    //Setup Accept Header
    MediaTypeWithQualityHeaderValue acceptHeader = MediaTypeWithQualityHeaderValue.Parse("application/json;odata=verbose");
    httpClient.DefaultRequestHeaders.Accept.Add(acceptHeader);

    //... do other stuff
}
like image 103
Kiran Avatar answered Nov 09 '22 18:11

Kiran