如何将配置文件参数添加到C#中的内容类型标题?
我试图设置我的如何将配置文件参数添加到C#中的内容类型标题?,c#,.net,rest,dotnet-httpclient,C#,.net,Rest,Dotnet Httpclient,我试图设置我的HttpClientPost请求的content-type,并使用profile参数,但当我更改内容类型时,会引发异常: “值'application/json;profile={URL HERE}'的格式为 无效。“ 作为参考,我发现了以下问答: 如果创建一条HttpRequestMessage并使用client.sendsync(),则可以将参数添加到request.Content.Headers.ContentType.parameters var client = new
HttpClient
Post请求的content-type
,并使用profile参数,但当我更改内容类型时,会引发异常:
“值'application/json;profile={URL HERE}'的格式为
无效。“
作为参考,我发现了以下问答:
如果创建一条HttpRequestMessage并使用client.sendsync(),则可以将参数添加到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
。否则你会遇到麻烦
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);