Handling 415 Unsupported Media Type in .NET Core API

By FoxLearn 1/10/2025 7:53:51 AM   66
In .NET Core APIs, the default content type for incoming requests is application/json.

This means that if you leave out the Content-Type header or specify a different content type, you may encounter a "415 Unsupported Media Type" error.

Handling a Custom Content Type

For instance, imagine you're developing an API endpoint to capture Content Security Policy (CSP) Violation Reports. These reports are typically sent with the application/csp-report content type, which is different from the default application/json. If you attempt to handle this report without properly configuring the API to accept the custom content type, you’ll face the 415 error.

To resolve this, you need to configure your API to support application/csp-report in addition to the default application/json. This can be done by adding the custom media type to the list of supported input formats in the ConfigureServices method.

In your Startup.cs (or Program.cs if using .NET 6 or later), within the ConfigureServices method, you can add the application/csp-report content type to the supported media types list as shown below:

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

With this configuration, your endpoint will now accept both application/json and application/csp-report content types, allowing the API to handle both JSON payloads and CSP violation reports.

Handling Requests Without a Content-Type

But what if the request does not include a Content-Type header at all? In such cases, the endpoint will need to handle the request differently.

If an endpoint is designed to accept any content type (or none at all), you can read the incoming data as a raw stream rather than trying to deserialize it into a strongly-typed model. This allows you to process the content regardless of the media type.

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

namespace MyApp
{
    [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();
                // Process the content (For testing, we simply return it)
                return base.Ok(message);
            }
        }
    }
}

In this example, the controller reads the incoming request body as a raw string using a StreamReader. This way, the endpoint can handle requests without a Content-Type header.

To avoid the "415 Unsupported Media Type" error in your .NET Core API, ensure that you configure the API to accept all the relevant content types. If you're working with custom content types or need to handle requests without a Content-Type, you can read the request body directly as a stream.