簡體   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