繁体   English   中英

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

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

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

“值 '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());

如果您创建一个HttpRequestMessage并使用客户端。 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..
}

您不需要使用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 否则你会遇到这个 dotnet 错误

暂无
暂无

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

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