Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何将配置文件参数添加到C#中的内容类型标题?_C#_.net_Rest_Dotnet Httpclient - Fatal编程技术网

如何将配置文件参数添加到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);