简体   繁体   English

ajax 发布到 MVC controller 失败,出现 400 错误请求

[英]ajax post to MVC controller failed with 400 Bad Request

I ajax post a complex object to a.Net 5.0 controller (not a WebAPI controller).我 ajax 将复杂的 object 发布到 a.Net 5.0 controller(不是 WebAPI 控制器)。 The declaration of the MVC controller and TypeScript are as below. MVC controller 和 TypeScript 的声明如下。 The [HttpPost] Edit action is invoked if I post with <input type='submit' value='Save' />.如果我使用 <input type='submit' value='Save' /> 发帖,将调用 [HttpPost] Edit 操作。 However, the controller's action is not invoked at all if I post through jQuery.ajax().但是,如果我通过 jQuery.ajax() 发布,则根本不会调用控制器的操作。 The browser console says "POST https://localhost:44381/Question/Edit 400 (Bad Request)".浏览器控制台显示“POST https://localhost:44381/Question/Edit 400 (Bad Request)”。 I read many code samples and nothing indicates anything wrong with the code.我阅读了许多代码示例,没有任何迹象表明代码有任何问题。 Does anyone know why?有谁知道为什么?

在此处输入图像描述

 namespace theProject.Controllers { public class BaseController: Controller { protected BaseController(IConfiguration configuration, ILogger logger) {.......(elided for brevity) } } }

 namespace theProject.Controllers { //ToDo: [Authorize] public class QuestionController: BaseController { public QuestionController(IConfiguration configuration, ILogger < QuestionController > logger): base(configuration, logger) {} [HttpPost] [ValidateAntiForgeryToken] public ActionResult Edit([FromBody] PostbackModel model) { if (ModelState.IsValid) { List < UserAnswer > newAnswers = model.NewAnswers; List < UserAnswer > oldAnswers = model.OldAnswers; List < UserAnswer > updatedAnswers = model.UpdatedAnswers; UserAnswer thisAnswer = new(); if (newAnswers.= null) thisAnswer = newAnswers.Find(x => x.StageName;= string.Empty). else if (oldAnswers.= null) thisAnswer = oldAnswers;Find(x => x.StageName.= string.Empty); else if (updatedAnswers:= null) thisAnswer = updatedAnswers,Find(x => x.StageName,= string.Empty), //ToDo. call webapi Question controller to persist the data to database return RedirectToAction(nameof(Edit). new { stage = thisAnswer,StageName; personName = thisAnswer,personName; custID = thisAnswer.custID.ToString(), redirectFrom = "Edit" }); } else { return RedirectToAction("Index", "Home"); } }

 let postBackModel: AjaxPostbackModel = < AjaxPostbackModel > {}; postBackModel.NewAnswers = newAnswers postBackModel.OldAnswers = oldAnswers; postBackModel.UpdatedAnswers = updatedAnswers; let thisUrl: string = $('form').prop('action'); $.ajax({ type: "POST", url: thisUrl, data: JSON.stringify(postBackModel), contentType: 'application/json; charset=utf-8', }).done(function(result) { $('.spinnerContainer').hide(); console.log('postback result', result.message); console.log('inserted entities', result.insetedEntities); dialogOptions.title = 'Success'; $('#dialog').text('Data is saved. ' + result.message).dialog(dialogOptions); }).fail(function(error) { console.log('postback error', error); $('.spinnerContainer').hide(); dialogOptions.title = error.statusText; dialogOptions.classes = { 'ui-dialog': 'my-dialog', 'ui-dialog-titlebar': 'my-dialog-header' } $('#dialog').text('Data is not saved').dialog(dialogOptions) });

Since you use [ValidateAntiForgeryToken] in action,you need to add the following code to your ajax to add antoforgery token to header.由于您在操作中使用了[ValidateAntiForgeryToken] ,因此您需要将以下代码添加到您的 ajax 以将防伪令牌添加到 header。

headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM