【问题标题】:Posting jQuery Datatable in ASP.NET Core causes 400 error在 ASP.NET Core 中发布 jQuery 数据表会导致 400 错误
【发布时间】:2019-06-19 11:31:30
【问题描述】:

我在前端设置了一个DataTables 表,它具有服务器端处理功能,因为它是一个大型数据集。我已经如下设置了 Ajax 调用,以回发到同一应用程序中的 MVC 控制器。

Ajax 调用:

ajax: {
    url: '/test',
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    data: function (d) {
        return JSON.stringify(d);
    }
}

控制器:

[Route("[controller]")]
[AllowAnonymous]
public class TestController : Controller
{
    [HttpPost]
    public IActionResult Post([FromBody]DataTablesRequest request)
    {
        // Content removed for brevity
        return Ok();
    }
}

由于某种原因,我总是收到 400 错误,并且控制器操作永远不会被击中。我认为这可能与我还实现了 .NET Identity 的事实有关,所以这可能是一个授权问题,但添加 [AllowAnonymous] 属性并没有帮助,我还尝试将 xhrFields: { withCredentials: true } 添加到 Ajax 调用中没有区别。

顺便说一下,DataTablesRequest 模型看起来像这样:

public class DataTablesRequest
{
    public int Draw { get; set; }
    public int Start { get; set; }
    public int Length { get; set; }
    public DataTablesOrder[] Order { get; set; }
    public DataTablesColumn[] Columns { get; set; }
    public DataTablesSearch Search { get; set; }
}

public class DataTablesOrder
{
    public int Column { get; set; }
    public string Dir { get; set; }
}

public class DataTablesColumn
{
    public string Data { get; set; }
    public string Name { get; set; }
    public bool Searchable { get; set; }
    public bool Orderable { get; set; }
    public DataTablesSearch Search { get; set; }
}

public class DataTablesSearch
{
    public string Value { get; set; }
    public bool Regex { get; set; }
}

...这是在正文中发送的 JSON 示例:

{  
   "draw":1,
   "columns":[  
      {  
         "data":"col1",
         "name":"",
         "searchable":true,
         "orderable":true,
         "search":{  
            "value":"",
            "regex":false
         }
      },
      {  
         "data":"col2",
         "name":"",
         "searchable":true,
         "orderable":true,
         "search":{  
            "value":"",
            "regex":false
         }
      },
      {  
         "data":"col3",
         "name":"",
         "searchable":true,
         "orderable":true,
         "search":{  
            "value":"",
            "regex":false
         }
      },
      {  
         "data":"col4",
         "name":"",
         "searchable":true,
         "orderable":true,
         "search":{  
            "value":"",
            "regex":false
         }
      }
   ],
   "order":[  
      {  
         "column":1,
         "dir":"desc"
      }
   ],
   "start":0,
   "length":25,
   "search":{  
      "value":"",
      "regex":false
   }
}

更新:

看起来这实际上与 SSL 有关。我刚刚在 Postman 中发送了请求并检查了 Postman 控制台,显示如下:

【问题讨论】:

  • 是的 - datatables.net
  • 明白了!等待回答!
  • API 控制器?
  • 我已经尝试过 API 控制器和普通的 MVC 控制器。都没有奏效。我也尝试添加 [ApiController] 属性,但没有帮助。
  • 检查我更新的答案!您的问题与路线有关。路线不正确。

标签: javascript ajax asp.net-core datatables asp.net-core-mvc


【解决方案1】:

这是因为您的 DataTable ajax 帖子没有正确获取路由。所以为了简单起见,先把[Route("[controller]")]从Controller中去掉,然后写成如下:

'ajax': {
     'url': '@Url.Action("Post", "Test")',
     'method': 'POST',
     'contentType': 'application/json',
     'data': function (d) {
          return JSON.stringify(d);
     }
 }

我已经从工作代码中发布了这个。

如果你需要整个东西,那么它如下:

var dataTable = $("#yourDataTableId").DataTable({
            'processing': true,
            'serverSide': true,
            "order": [[0, 'desc']],
            'ajax': {
                'url': '@Url.Action("Post", "Test")',
                'method': 'POST',
                'contentType': 'application/json',
                'data': function (d) {
                    return JSON.stringify(d);
                }
            },
            "lengthMenu": [[5, 10], [5, 10]],
            "lengthChange": true,
            "searching": true,
            "scrollX": true,
            fixedColumns: {
                leftColumns: 1,
                rightColumns: 1
            },
            'columns': [
                { data: "yourColumnName", name: "YourColumnName" }

                //Other columns

            ]
 });

【讨论】:

  • 我的 DataTables 设置在 JavaScript 文件中,而不是在我的视图中,因此我无法访问 Razor 辅助方法。另外,我刚刚对其进行了测试,@Url.Action("Post", "Test") 也输出了“/Test”,这就是我将 url 设置为的内容。
  • 你肯定错过了什么!这是 100% 可行的代码。试着找出问题所在。祝你一切顺利!
  • 一个问题,你能提供团队查看器的远程访问,以便我可以说出问题吗?
【解决方案2】:

你应该继承 ApiController 而不是Controller

来自Get Started with ASP.NET Web API的示例

using ProductsApp.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Http;

namespace ProductsApp.Controllers
{
    public class ProductsController : ApiController
    {
        Product[] products = new Product[] 
        { 
            new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, 
            new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, 
            new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } 
        };

        public IEnumerable<Product> GetAllProducts()
        {
            return products;
        }

        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault((p) => p.Id == id);
            if (product == null)
            {
                return NotFound();
            }
            return Ok(product);
        }
    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 2020-11-15
  • 2018-11-06
  • 2016-05-06
  • 1970-01-01
  • 2021-02-25
  • 2022-01-24
  • 2022-01-10
相关资源
最近更新 更多