【问题标题】:How do I add the profile parameter to the content-type header in C#?如何将配置文件参数添加到 C# 中的内容类型标头?
【发布时间】:2017-02-15 09:23:16
【问题描述】:

我正在尝试设置我的 HttpClient Post 请求的 content-type,并使用 profile 参数,但是当我更改内容类型时,我得到一个异常:

"value 'application/json; profile={URL HERE}' 的格式为 无效。”

作为参考,我找到了这个问答:Zoopla Sandbox with cURL http header error

X509Certificate2 cert = new X509Certificate2("cert.pfx", "PASSWORD");
WebRequestHandler handler = new WebRequestHandler();
handler.ClientCertificates.Add(cert);
var client = new HttpClient(handler);                
client.BaseAddress = new Uri("https://realtime-listings-api.webservices.zpg.co.uk");
var stringContent = new StringContent(propertyData, Encoding.UTF8, "application/json; profile=http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json");
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var response = await client.PostAsync("/sandbox/v1/listing/list", stringContent);
return _resultFactory.Create(true, await response.Content.ReadAsStringAsync());

【问题讨论】:

    标签: c# .net rest dotnet-httpclient


    【解决方案1】:

    如果你创建一个HttpRequestMessage并使用client.SendAsync(),你可以将参数添加到request.Content.Headers.ContentType.Parameters

    var client = new HttpClient();
    using (HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://realtime-listings-api.webservices.zpg.co.uk/sandbox/v1/listing/list"))
    {
        request.Content = new StringContent("propertyData", Encoding.UTF8, "application/json");
        request.Content.Headers.ContentType.Parameters.Add(
            new NameValueHeaderValue("profile", "http://realtime-listings.webservices.zpg.co.uk/docs/v1.1/schemas/listing/list.json")
            );
        var response = await client.SendAsync(request);
        //Handle response..
    }
    

    【讨论】:

      【解决方案2】:

      您不需要使用HttpRequestMessage,但您需要通过 NameValueHeaderValue 参数将配置文件值添加为带引号的字符串:

      var content = new StringContent(request.ToJson(), Encoding.UTF8);
      content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
      content.Headers.ContentType.Parameters.Add(new NameValueHeaderValue("profile", "\"https://realtime-listings.webservices.zpg.co.uk/docs/v1.2/schemas/listing/update.json\""))
      httpClient.PostAsync("listing/update", content);
      

      这将绕过FormatException。否则你会遇到this dotnet bug

      【讨论】:

        猜你喜欢
        • 2022-09-26
        • 2019-08-27
        • 2018-07-22
        • 2016-10-27
        • 1970-01-01
        • 2014-04-22
        • 1970-01-01
        • 2016-01-01
        • 1970-01-01
        相关资源
        最近更新 更多