415-Unsupported-Media-Type when posting a form using ajax to a ASP.NET Core 3.1 controller

Viewed 3569

I have an ASP.NET Core 3.1 based project where I validate forms using jQuery-Unobtrusive and jQuery-Unobtrusive-AJAX. When the form is submitted, I get an HTTP 415 error.

Follow is my controller's code.

[Route("api/[controller]"), ApiController]
public class ScheduleController : ControllerBase
{
    private readonly IEmailSender Emailer;

    public ScheduleController(IEmailSender emailer)
    {
        Emailer = emailer;
    }

    [HttpPost(Name = "Schedule"), ValidateAntiForgeryToken]
    public async Task<ActionResult<bool>> Schedule([FromBody]Schedule viewModel)
    {
        if (!ModelState.IsValid)
        {
            return Problem(false);
        }

        bool sent = await Emailer.SendEmailAsync("Schedule Request", viewModel.GetMessage());

        return Ok(sent);
    }
}

Here is a stripped-down version of my form

<form asp-route="Schedule" data-ajax="true" data-ajax-method="POST" data-ajax-begin="onBegin" data-ajax-failure="onFailed" data-ajax-success="onSuccess">
@* fields... *@
</form>

I tried changing the [FromBody] to [FromForm] and tried removing it completely but nothing seems to be fixing this error.

Here is the raw request header

Host: localhost:1234
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:75.0) Gecko/20100101 Firefox/75.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 330
Origin: https://localhost:1234
Connection: keep-alive
Cookie: [Removed from simplicity]

Here is the raw request body

PropertyId=123&Date=4%2F11%2F2020+12%3A00%3A00+AM&Time=4%2F10%2F2020+11%3A00%3A00+AM&Phone=(123)+456-7890&Email=&__RequestVerificationToken=CfDJ8K77JmNhv79HurCngEMVfZh4LUSvtnAQfHGD3p3cO5bsB1NgI--P5JuhfG62F5igdXq2ers_V7MoMDFNVQTVuF9qGqTslDTkDPdcqIFD4wUkREhD6vHvSrdbqT24LWXTfr9Nu124A2OVAlJZa_xLCvs&X-Requested-With=XMLHttpRequest
1 Answers

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

When your Content-Type is application/x-www-form-urlencoded you must change [FromBody] to [FromForm].

If you use [FromForm] add [Consumes("application/x-www-form-urlencoded")] on action to accept application/x-www-form-urlencoded content-type

[Consumes("application/x-www-form-urlencoded")]
[HttpPost(Name = "Schedule"), ValidateAntiForgeryToken]
public async Task<ActionResult<bool>> Schedule([FromForm]Schedule viewModel)
{
    if (!ModelState.IsValid)
    {
        return Problem();
    }

    bool sent = await Emailer.SendEmailAsync("Schedule Request", viewModel.GetMessage());

    return Ok(sent);
}

ConfigureService

services.AddMvc(config =>
    {
        // Add XML Content Negotiation
        config.RespectBrowserAcceptHeader = true;
        config.ReturnHttpNotAcceptable = true;
        config.InputFormatters.Add(new XmlSerializerInputFormatter());
        config.OutputFormatters.Add(new XmlSerializerOutputFormatter());
    });

this link maybe helpful for you.

if you need use the [FromBody] you must change Content-Type to application/json instead of application/x-www-form-urlencoded.

Related