Dotnet core – 415 unsupported media type error? Easy fix2 min read

Prologoue

Hello friends! It’s been a while, again! I hope you are all going well and that this new 2021 is going to be better than the last 2020 year, for all of us.

My New Years’ resolutions are to head back to posting each week blog post and to make one Youtube video per month!
So let’s see how’s that going to work out. ๐Ÿ™‚

So here is my new blog post in 2021:

415 Unsupported Media Type error

If you just started with .NET API, most certainly you will experience this kind of an error.
You will have your method ready with some param and [FromBody] attribute set and you will expect JSON results from your method.

I.e.:

[ApiController]
public class MyController : Controller {
 [HttpPost]
 public async Task<IActionResult> SomeMethod([FromBody] CustomModel model) { //... }
 }

and when you fire a postfrom Postman, baaaam.


(Image source: https://www.keycdn.com/support/415-unsupported-media-type)

You get this: 415 unsupported media type error and you react like: โ€œWTF!?!? What did I do wrong!?!โ€. Scary error… I mean, all errors are scary, right!? ๐Ÿ™‚ But donโ€™t worry, I will show you the fix! But firstly let me explain, why did you get this error!

Hereโ€™s the thing, by default when you fire a postin Postman, request type is set to โ€œTEXTโ€.

And on the other side our (Asp.Net Core) backend cannot distinguish between json or text input params.

So in order to fix this issue we have 2 (two) options:

Fix number one:

We must ensure that we’re using raw and that our request is in โ€œJSONโ€format. 

But there is another one as well. We can use another fix by creating middleware in our Asp.Net Core application.

Fix number two:

So we will create fix to accept body params inputs without headers: 

Accept/Content-Types: application/json

And to use this fix, we need to put the following code inside our ConfigureServices method in Startup.cs:

            services.AddMvc(options =>
            {
                options.AllowEmptyInputInBodyModelBinding = true;
                foreach (var formatter in options.InputFormatters)
                {
                    if (formatter.GetType() == typeof(SystemTextJsonInputFormatter))
                        ((SystemTextJsonInputFormatter)formatter).SupportedMediaTypes.Add(
                            Microsoft.Net.Http.Headers.MediaTypeHeaderValue.Parse("text/plain"));
                }
            }).AddJsonOptions(options =>
            {
                options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
            });

What did we just do?

Well, we created our custom middleware where we provided our custom formatter. 

Basically we added Json formatting to plain text.

This way we removed the necessity for adding JSON header when sending our body input params.

(Visited 34 times, 1 visits today)

Leave a comment

Your email address will not be published. Required fields are marked *