Is it possible to set the Default Content-Type to “application/json;v=2.0”

半城伤御伤魂 提交于 2020-01-04 07:30:48

问题


Is it possible to set the Default Content-Type to "application/json;v=2.0". I say default because I'm using a HttpClient class and I use the DefaultRequestHeaders to set my proxies default values.

I followed this example to create my headers https://stackoverflow.com/a/10679340/196526 but I also use versioning and information about versioning is saved in ContenT-Type

public class BankAccountProxy
{
    public void SetToken()
    {
        Client = new HttpClient();
        Client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["ApiRoute"]);
        Client.DefaultRequestHeaders.Accept.Clear();
        Client.DefaultRequestHeaders.Add("Token", ApiInformations.ApiToken);
        Client.DefaultRequestHeaders
            .Accept
            .Add(new MediaTypeWithQualityHeaderValue($"application/json;v=2.0"));
    }

    public async Task<IEnumerable<BankAccount>> Get()
    {
        HttpResponseMessage response = await Client.GetAsync($"/api/BankAccount/");
        response.EnsureSuccessStatusCode();
        IEnumerable<BankAccount> bankAccount;
        bankAccount = await response.Content.ReadAsAsync<IEnumerable<BankAccount>>();
        return bankAccount;
    }
}

When I run this code I get a

Exception message: The format of value 'application/json;v=2.0' is invalid.

Because of the v=2.0 that is probably not a valid MediaTypeWithQualityHeaderValue.

What I want is to be sure I always send the version information in my Content-Type header value. How can I initialize it? How can I tell my code my default content type is not a quality header but a valid one.

For information here is my query perfectly working on Postman:

来源:https://stackoverflow.com/questions/55644730/is-it-possible-to-set-the-default-content-type-to-application-jsonv-2-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!