【问题标题】:AJAX POST request Returning 400 errorAJAX POST 请求返回 400 错误
【发布时间】:2018-01-28 18:49:39
【问题描述】:

我正在尝试使用 jQuery AJAX 使用 POST 方法将数据发送到控制器。这是我用来发送数据的代码:

 $('#save_new').on('click', function () {
                var category_name = $('#new_category').val();
                var description = $('#new_description').val();

                $.ajax({
                         type: 'POST',
                         url:"/admin/news-category/addNew",
                         data: JSON.stringify({ category_name:     category_name  ,description:description}),
                         contentType: 'application/json; charset=utf-8',
                         dataType:'json',
                         success: function (ctct) {
                            alert("success function run,");
                        },
                        error: function () {
                            alert("Failed to save news category.");
                        }
                });
            });

这是我的控制器:

[Route("/admin/news-category")]
public class NewsCategoryController : Controller
{
    [Route("addNew")]
    [HttpPost]
    public IActionResult addNew(string category_name,string description)
    {
        NewsCategory news_category = new NewsCategory();
        if (ModelState.IsValid)
        {
           // some statements here
            return Json(new { success = true, responseText = "News Category added successfully" });
        }
        return Json(new { success = false, responseText = "Invalid input datas.Please enter valid datas and try again" });
    }
}

执行尚未到达控制器中的 addNew 操作。问题的原因是什么?

更新 1:这是我在 Startup

中的 MapRoute
   app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

更新 2:这是我的网络选项卡的样子:

【问题讨论】:

  • 你能专门用 MapRoutes 发布你的启动吗?
  • @mvermef 我更新了我的问题。可以看看吗?

标签: jquery ajax asp.net-core-mvc


【解决方案1】:

我收到这个错误是因为我添加了

 services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });

Startup 类中的 ConfigureServices 方法中。

从看来,我没有发送 AntiForgeryToken,因为我没有使用 Form 标签助手。默认情况下,由于那个 MiddleWare,我的操作是检查不是通过 AJAX 请求 发送的 AntiForgeryToken。因此,我使用 [IgnoreAntiforgeryTokenAttribute]addNew 操作中删除了验证。

[Route("addNew")]
  [HttpPost]
  [IgnoreAntiforgeryTokenAttribute]

这解决了我的问题。 我希望这对遇到同样问题的其他人有所帮助。

【讨论】:

  • 这会禁用 AJAX 调用的安全性,让您面临 CSRF 攻击。您可以(并且应该)将令牌与 AJAX 请求一起发送并设置 AntiForgery 服务以使用它。有关详细信息,请参阅此答案:stackoverflow.com/a/48407537/1173702
【解决方案2】:

简短回答:您需要了解路线图以及何时使用它们...

长答案:参考注释行

  app.UseMvc(routes =>
        {

           routes.MapRoute(
             name: "newcatroute",
             template: "admin/news-category/{action}/{id?}"
             defaults: new {controller="NewsCategory", action="Index"]);

            //your route CAN'T be caught by default... because 
            //of the `admin/news-cateogry`since it doesn't know 
            //how to map that to any controller even with that route 
            //attribute attached to the Controller its self.               


            //HONEY POT ROUTE ... WORKS most of the time, unless you put some flashy extras in...!
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });



public class NewsCategoryController : Controller
{

   public IActionResult Index(){
         return View();
   }

   [HttpPost]
   public IActionResult addNew(string category_name,string description)
   {
     //...
   }
}

使用上面的路由映射,它会将任何对“admin/news-category”的调用映射到该控制器,任何与该控件相关的操作都会被发现。

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing#using-routing-middleware

【讨论】:

  • 我可以使用 /admin/news-category/index 访问同一控制器的索引操作。当我检查时,我看到 /admin/news-category/addNew 中显示了 400 错误。我也尝试过使用上述路线。
【解决方案3】:

这很可能是方法签名中的参数有问题。 默认情况下,使用 POST 时,您应该在消息正文中定义要发送的数据。 因此,我建议您创建一个像这样保存这些参数的类

public class MsgDto
{
    public string category_name { get; set; }
    public string description { get; set; }
}

然后告诉你的方法使用 FromBody 属性从消息体中读取这些值

[Route("addNew")]
[HttpPost]
public IActionResult addNew([FromBody]MsgDto msg)
{
    // read msg.category_name or msg.description
}

【讨论】:

  • 对不起先生,这不起作用。我在 HTTPS 中运行我的应用程序。但是,当我从操作中删除 HttpPost 并通过查询字符串发送数据时,一切正常。但我实际上希望那是 HttpPost。
  • @DotNetdeveloper 好的,奇怪.. 听起来好像有问题然后在 ajax 请求中.. 你可以尝试我的解决方案并将正文指定为 JSON.stringify({ "category_name":category_name ,"描述”:描述})
  • 对不起,先生,这也没有帮助。我已经更新了我的问题以显示响应和请求标头。你能看一下吗?
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-23
  • 2014-01-15
  • 1970-01-01
  • 2017-03-26
相关资源
最近更新 更多