使用 ajax 将表单发布到 ASP.NET Core 3.1 控制器时出现 415-Unsupported-Media-Type

Joh*_*ohn 3 jquery unobtrusive-validation asp.net-core asp.net-core-3.0 asp.net-core-3.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我的表格的精简版本

<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>
Run Code Online (Sandbox Code Playgroud)

我尝试更改[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]
Run Code Online (Sandbox Code Playgroud)

这是原始请求正文

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
Run Code Online (Sandbox Code Playgroud)

Far*_*ani 8

HTTP 415 Unsupported Media Type 客户端错误响应代码表示服务器拒绝接受请求,因为负载格式为不受支持的格式。

格式问题可能是由于请求指示的内容类型或内容编码造成的,或者是由于直接检查数据造成的。

当您的Content-Type是 时,application/x-www-form-urlencoded您必须更改[FromBody][FromForm].

如果您使用[FromForm]添加[Consumes("application/x-www-form-urlencoded")]操作来接受application/x-www-form-urlencoded内容类型

[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);
}
Run Code Online (Sandbox Code Playgroud)

配置服务

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

这个链接也许对你有帮助。

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