Quantcast
Channel: briancaos – Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 276

Handling “415 Unsupported Media Type” in .NET Core API

$
0
0

The default content type for .NET Core API’s is application/json. So if the content-type is left out, or another content type is used, you will get a “415 Unsupported Media Type”:

415 Unsupported Media Type from Postman

This is for example true if you develop an endpoint to capture Content Security Policy Violation Reports. Because the violation report is sent with the application/csp-report content type.

To allow another content-type, you need to specify which type(s) to receive. In ConfigureServices, add the content-type to use to the SupportedMediaTypes:

public void ConfigureServices(IServiceCollection services)
{
  ...
  ...
  // Add MVC API Endpoints
  services.AddControllers(options =>
  {
    var jsonInputFormatter = options.InputFormatters
        .OfType<Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter>()
        .Single();
    jsonInputFormatter.SupportedMediaTypes.Add("application/csp-report");
  }
  );
  ...
  ...
}

Now your endpoint will allow both application/json and application/csp-report content types.

BUT WHAT IF THERE IS NO CONTENT TYPE?

To allow an endpoint to be called without any content-type, you also allow everything to be posted to the endpoint. The endpoint will read the posted content using a streamreader instead of receiving it from a strongly typed parameter.

The endpoint cannot be called using your Swagger documentation.

using Microsoft.AspNetCore.Mvc;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace MyCode
{
  [ApiController]
  [Route("/api")]
  public class TestController : ControllerBase
  {
    [HttpPost("test")]
    public async Task<IActionResult> Test()
    {
      using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
      {
        string message = await reader.ReadToEndAsync();
        // Do something with the received content. For 
        // test pusposes, I will just output the content:
        return base.Ok(message);
      }
    }
  }
}

MORE TO READ:


Viewing all articles
Browse latest Browse all 276

Trending Articles