是否可以将默认内容类型设置为"application/json; v = 2.0"? [英] Is it possible to set the Default Content-Type to "application/json;v=2.0"

查看:228
本文介绍了是否可以将默认内容类型设置为"application/json; v = 2.0"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将默认内容类型设置为"application/json; v = 2.0".我说默认值是因为我正在使用HttpClient类,并且使用DefaultRequestHeaders将代理设置为默认值.

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 to default values.

我按照此示例创建了标头 https://stackoverflow.com/a/10679340/196526 ,但是我也使用版本控制,有关版本控制的信息保存在ContenT-Type

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

异常消息:值'application/json; v = 2.0'的格式为 无效.

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

由于v = 2.0可能不是有效的MediaTypeWithQualityHeaderValue.

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

我要确保我始终在Content-Type标头值中发送版本信息.如何初始化?我该如何告诉我的代码,我的默认内容类型不是质量标头,而是有效的标头.

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.

有关信息,这是我对Postman的完美查询:

For information here is my query perfectly working on Postman:

推荐答案

TL; DR

使用此代码:

TL;DR

Use this code:

    class Program
    {
        static async Task Main(string[] args)
        {
            try
            {
                var client = new HttpClient { BaseAddress = new Uri("https://contenttypev2.free.beeceptor.com") }; // interceptor
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Add("Token", "SOME_TOKEN"); // simplified

                var response = await client.GetJson2Async("/api/BankAccount/");
                response.EnsureSuccessStatusCode();
                var data = await response.Content.ReadAsStringAsync(); // simplified
                Console.WriteLine(data);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            finally
            {
                Console.ReadLine();
            }
        }
    }

    class Json2Content : StringContent
    {
        public Json2Content(string content) : this(content, Encoding.Default) { }

        public Json2Content(string content, Encoding encoding) : base(content, encoding)
        {
            this.Headers.Clear();
            this.Headers.ContentType = new MediaTypeHeaderValue("application/json");
            this.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("v", "2.0"));
            if (!encoding.Equals(Encoding.Default)) this.Headers.ContentType.CharSet = encoding.HeaderName;
        }
    }

    static class Json2Extensions
    {
        public static Task<HttpResponseMessage> GetJson2Async(this HttpClient client, string requestUri, string content = "", Encoding encoding = default)
        {
            var request = new HttpRequestMessage(HttpMethod.Get, requestUri) { Content = new Json2Content(content, encoding ?? Encoding.Default) };
            return client.SendAsync(request);
        }
    }

这是结果:

carlosfigueira 所述:

内容类型是内容的标头,而不是请求的标头

The content type is a header of the content, not of the request

因此,像在此处一样设置Accept标头:

So setting the Accept header like you did here:

Client.DefaultRequestHeaders
  .Accept
  .Add(new MediaTypeWithQualityHeaderValue($"application/json;v=2.0"));

不会帮助您实现目标.

要简化JSON v2内容类型的使用,可以使用上面的包装器类以及提供的扩展方法.

To simplify use of JSON v2 content type, you can use the wrapper class above as well as the extension method provided.

确定要设置Content-Type标头吗?在GET请求中包含内容很少见. 如果要向服务器发送信号,表示希望 接收 JSON v2响应,则应在Accept标头中执行此操作.甚至您所引用的 API版本控制文件该问题的注释中显示版本号可以在Accept标头 Content-Type标头中设置.如果有内容,您仍然可以使用'Accept'标头设置版本,您可以将其作为默认设置,如下所示:

Are you sure you want to set the Content-Type header? It is very uncommon to have content in a GET request. If you want to signal the server that you wish to receive JSON v2 response, you should do it in the Accept header. Even the API versioning document you have referenced in the comments to the question shows that the version number could be set in the Accept header or the Content-Type header. When there is content you can still, probably, use the 'Accept' header to set the version and you can do that as a default like so:

var client = new HttpClient { BaseAddress = new Uri("https://contenttypev2.free.beeceptor.com") }; // interceptor
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Add("Token", "SOME_TOKEN"); // simplified
client.DefaultRequestHeaders.Accept.Clear();
var json2MediaType = new MediaTypeWithQualityHeaderValue("application/json");
json2MediaType.Parameters.Clear();
json2MediaType.Parameters.Add(new NameValueHeaderValue("v", "2.0"));
client.DefaultRequestHeaders.Accept.Add(json2MediaType);

var response = await client.GetAsync("/api/BankAccount/");
...

导致:

这篇关于是否可以将默认内容类型设置为"application/json; v = 2.0"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆