Search code examples
c#asp.netasp.net-mvc-4asp.net-web-apidotnet-httpclient

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.


Solution

  • 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
    }