简体   繁体   English

如何将配置文件参数添加到 C# 中的内容类型标头?

[英]How do I add the profile parameter to the content-type header in C#?

I'm trying to set the content-type of my HttpClient Post request, and use the profile parameter, but when I change the content type I get an exception thrown:我正在尝试设置HttpClient Post 请求的content-type ,并使用 profile 参数,但是当我更改内容类型时,抛出异常:

"The format of value 'application/json; profile={ URL HERE }' is invalid." “值 'application/json; profile={ URL HERE }' 的格式无效。”

For reference, I found this Q&A: Zoopla Sandbox with cURL http header error作为参考,我发现了这个问答: 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());

If you create a HttpRequestMessage and use client.如果您创建一个HttpRequestMessage并使用客户端。 SendAsync() , you can add the parameters to request.Content.Headers.ContentType.Parameters 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..
}

You don't need to use HttpRequestMessage but you do need to add the profile value as a quoted string via the NameValueHeaderValue parameter:您不需要使用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);

This will get round the FormatException .这将绕过FormatException Otherwise you will run into this dotnet bug .否则你会遇到这个 dotnet 错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM