StatusCode: 415, ReasonPhrase: «Неподдерживаемый тип носителя», версия: 1.1, содержимое: System.Net.Http.StreamContent - PullRequest
0 голосов
/ 08 октября 2019

Я хотел бы опубликовать новый ресурс в конечной точке, используя .NET HttpClient. Однако я получаю сообщение об ошибке. Выполнив ту же операцию с теми же заголовками и тем же содержимым в Postman, операция post прошла без ошибок. В сообщениях об ошибках говорится:

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
}

Я также пытался использовать метод PostAsync непосредственно для экземпляра HttpClient вместо использования экземпляра HttpRequestMessage. Однако эта опция не работает, так как я хотел бы установить свои пользовательские заголовки в запросе. Параметр DefaultRequestHeaders.Add, кажется, не поддерживает это. Я использую код, предложенный для аналогичного вопроса в Пользовательский заголовок для запроса Httpclient . Ниже приведен мой код.

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'. Другие ответы на ту же проблему указывают на то, что это ошибка сервера. В моем случае я так не думаю, так как я достигаю правильного результата в Почтальоне, как указано здесь .

...