Van*_*nel 2 c# rest httpclient asp.net-web-api windows-store
我正在使用C#和.NET Framework 4.5.1开发Windows 8.1 Store应用程序.
我正在尝试对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;
}
Run Code Online (Sandbox Code Playgroud)
如果我更改此行:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(jsonContent));
Run Code Online (Sandbox Code Playgroud)
有了这个:
response = await httpClient.PostAsync(resourceUri, new HttpStringContent(string.Empty));
Run Code Online (Sandbox Code Playgroud)
有用.我没有获得415状态代码.
jsonContent 价值是:
{"UserName":"My Name","Provider":"Facebook","ExternalAccessToken":"Access token omitted"}
因为我没有在互联网上找到任何类似的代码,我在这个问题上只有4个观点; 我将分享答案.
我已修复此问题,使用以下代码更改帖子:
response = await httpClient.PostAsync(resourceUri,
new HttpStringContent(jsonContent, UnicodeEncoding.Utf8, "application/json"));
Run Code Online (Sandbox Code Playgroud)
您可以在HttpStringContent构造函数上传递"Content-Type" .更多信息在这里.
| 归档时间: |
|
| 查看次数: |
1700 次 |
| 最近记录: |