Error 415 when posting to ASP.Net Core WebAPI using XMLHttpRequest

Don't know why yet, I'm still pretty new to .Net Core Web API's. I removed the controller attribute [ApiController] and everything fell into place.

In my situation, I have a MVC interface & WebApi on the same project. Hope this helps someone.


As Evan mentioned in his comment, your POST is turning into an OPTIONS when you make a cross-origin ajax request. Due to browsers' cross-origin security policies, your web api needs to tell the browser/js that your website is allowed to make ajax requests against it.

https://docs.microsoft.com/en-us/aspnet/core/security/cors

To setup CORS for your application add the Microsoft.AspNetCore.Cors package to your project.

Add the CORS services in Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}

If you follow the linked instructions, you can even use IApplicationBuilder.UseCors to further customize which sites are allowed.

For example:

app.UseCors(builder =>
    builder.WithOrigins("http://example.com")
           .AllowAnyHeader()
);

Postman is an app and therefore has the ability to exempt itself from cross-origin rules.


In my case the problem was that I put a FromBody attribute before my action parameter.

From:

[HttpPost("Contact")]
public async Task<IActionResult> NewContact([FromBody]Contact contact)

To:

[HttpPost("Contact")]
public async Task<IActionResult> NewContact(Contact contact)