我想使用.NET HttpClient将新资源发布到端点。但是,我收到一条错误消息。在Postman中使用相同的标题和相同的内容执行相同的操作,后操作成功完成,没有任何错误。错误消息指出:
StatusCode: 415, ReasonPhrase: 'Unsupported Media Type', Version: 1.1, Content: System.Net.Http.StreamContent, Headers:
{
X-Content-Type-Options: nosniff
X-Content-Type-Options: nosniff
X-UA-Compatible: IE=edge
X-Frame-Options: SAMEORIGIN
X-Generator: Drupal 8 (https://www.drupal.org)
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Cache-Control: must-revalidate, no-cache, private
Date: Tue, 08 Oct 2019 16:24:17 GMT
Server: Apache/2.4.39
Server: (Win64)
Server: OpenSSL/1.1.1c
Server: PHP/7.2.19
X-Powered-By: PHP/7.2.19
Content-language: en
Content-Type: application/vnd.api+json
Expires: Sun, 19 Nov 1978 05:00:00 GMT
}
我还尝试直接在HttpClient实例上使用PostAsync方法,而不是使用HttpRequestMessage实例。但是,此选项不起作用,因为我想在请求中设置自定义标头。 DefaultRequestHeaders.Add选项似乎不支持此功能。我正在按照Custom header to Httpclient request上类似问题的建议使用代码。下面是我的代码。
using Newtonsoft.Json;
using System;
using System.Net;
using System.Net.Http;
namespace ConsoleApp6
{
class Program
{
static void Main(string[] args)
{
//the string that needs to be posted to endpoint.
string dd = @"{'data': { 'type': 'node--settings','attributes': {'title': 'Mail Server3'}}}";
//outputting my text here to make sure that the text is a valid json.
Console.WriteLine(JsonConvert.DeserializeObject(dd));
//my http client using suggested solutions on the internet and here on stakeoverflow.
var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Post,
RequestUri = new Uri("http://localhost/pg/jsonapi/node/settings"),
Headers = {
{ HttpRequestHeader.Authorization.ToString(), "Basic YXBpOmFwaQ==" },
{ HttpRequestHeader.ContentType.ToString(), "application/vnd.api+json" }
},
Content = new StringContent(JsonConvert.DeserializeObject(dd).ToString())
};
//posting the data here to the endpoint and capturing the request.
var response = client.SendAsync(httpRequestMessage).Result;
//here is the response I am getting.
Console.WriteLine(response);
Console.ReadLine();
}
}
}
我希望该操作返回Status: 201 Created
。我收到的状态消息是StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'
。对同一问题的其他答案表明这是服务器错误。就我而言,我不这么认为,因为我在here中表示的Postman中取得了正确的结果。