在WinRT HttpClient上设置请求Content-Type

时间:2014-11-04 17:51:09

标签: c# rest asp.net-web-api httpclient windows-store

我正在使用C#和.NET Framework 4.5.1开发Windows 8.1商店应用程序。

我正在尝试对REST API执行POST,但是我使用以下代码获得了不支持的媒体类型:

public async Task<HttpResponseMessage> POST(string url, string jsonContent)
{
    Uri resourceUri;

    resourceUri = ValidateUri(url);

    HttpClient httpClient = new HttpClient();
    HttpResponseMessage response = new HttpResponseMessage();

    HttpRequestHeaderCollection headers = httpClient.DefaultRequestHeaders;

    // Try to add user agent to headers.
    if (headers.UserAgent.TryParseAdd(_userAgent))
        headers.UserAgent.ParseAdd(_userAgent);

    // Add Content-Type and Content-Length headers
    headers.Accept.Add(new HttpMediaTypeWithQualityHeaderValue("application/json"));

    response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));

    return response;
}

如果我更改此行:

response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));

有了这个:

response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));

有效。我没有获得415状态代码。

jsonContent值为:

{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}

1 个答案:

答案 0 :(得分:5)

因为我还没有在互联网上找到任何类似的代码,而我在这个问题上只有4个观点;我将分享答案。

我已修复此问题,使用以下代码更改帖子:

response = await httpClient.PostAsync(resourceUri,
    new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));

你可以通过&#34; Content-Type&#34;在HttpStringContent构造函数上。更多信息here