I would like to post a new resource to an endpoint using the .NET HttpClient. However, I am getting an error message. Doing the same operation with same headers and same content in Postman, the post operation succeeded without any errors. The error messages states that:
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
}
I also tried to use the PostAsync method direct on the HttpClient instance instead of using the HttpRequestMessage instance. However, this option is not working as I would like to set my custom headers in the request. The DefaultRequestHeaders.Add option seem not support this. I am using code as suggested on a similar question at Custom header to Httpclient request. Below is my code.
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();
}
}
}
I am expecting the operation to return Status: 201 Created
. The status message I am getting is StatusCode: 415, ReasonPhrase: 'Unsupported Media Type'
. Other answers to the same problem indicate this is a server error. In my case, I do not think so, since, I am achieving the correct result in Postman as indicated here.