AJAX POST请求返回400错误

时间:2018-01-28 18:49:40

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

我正在尝试使用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:这是启动

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

更新2:这是我的网络标签的样子: Network tab during inspection

3 个答案:

答案 0 :(得分:0)

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

长答案:参考评论专栏

  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

答案 1 :(得分:0)

这很可能是方法签名中的参数存在问题。 默认情况下,使用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
}

答案 2 :(得分:0)

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

 services.AddMvc(options =>
            {
                options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute());
            });
启动类的配置服务方法中

从视图来看,我没有发送 AntiForgeryToken ,因为我没有使用表单标签帮助器。默认情况下,由于 MiddleWare ,我的操作是检查 AntiForgeryToken ,但未通过 AJAX请求发送。因此,我使用 [IgnoreAntiforgeryTokenAttribute] addNew 操作中删除了验证。

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

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

相关问题