[使用ajax向ASP.NET Core 3.1控制器发布表单时,415-Unsupported-Media-Type

问题描述 投票:0回答:1

我有一个基于ASP.NET Core 3.1的项目,我在其中使用jQuery-Unobtrusive和jQuery-Unobtrusive-AJAX来验证表单。提交表单后,出现HTTP 415错误。

以下是我的控制器代码。

[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);
    }
}

这里是我的表格的精简版

<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>

我尝试将[FromBody]更改为[FromForm],并尝试将其完全删除,但似乎没有任何办法可以解决此错误。

这里是原始请求标头

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]

这里是原始请求正文

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
jquery asp.net-core unobtrusive-validation asp.net-core-3.0 asp.net-core-3.1
1个回答
0
投票

HTTP 415不受支持的媒体类型客户端错误响应代码表明服务器拒绝接受请求,因为有效负载格式为不受支持的格式。

格式问题可能是由于请求指示的Content-Type或Content-Encoding,或者是直接检查数据的结果。

[Content-Typeapplication/x-www-form-urlencoded时,必须将[FromBody]更改为FromForm

如果需要使用[FromBody],则必须将Content-Type更改为application/json,而不是application/x-www-form-urlencoded

并检查Content-Encoding

© www.soinside.com 2019 - 2024. All rights reserved.