如何将配置文件参数添加到C#中的content-type标头?

时间:2017-02-15 09:23:16

标签: c# .net rest dotnet-httpclient

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

  

"值' application / json的格式;个人资料= {这里的网址}'是   。无效"

作为参考,我发现了这个Q& A: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());

2 个答案:

答案 0 :(得分:0)

如果创建 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..
}

答案 1 :(得分:0)

您不需要使用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