jQuery DataTables 警告:table id={id} Ajax ASP.NET 核心项目中的错误状态代码 400

jQuery DataTables warning: table id={id} Ajax error status code 400 in ASP.NET Core project

我正在尝试在我的 ASP.NET 核心项目中使用 jQuery 数据table。我的控制器 class 具有以下代码:

[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
    private readonly IUsersService usersService;

    public UsersController(IUsersService usersService)
    {
        this.usersService = usersService;
    }

    [HttpPost("GetUsers")]
    public IActionResult GetUsers()
    {
        try
        {
            var draw = this.Request.Form["draw"].FirstOrDefault();
            var start = this.Request.Form["start"].FirstOrDefault();
            var length = this.Request.Form["length"].FirstOrDefault();
            var sortColumn = this.Request.Form["columns[" + this.Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
            var sortColumnDirection = this.Request.Form["order[0][dir]"].FirstOrDefault();
            var searchValue = this.Request.Form["search[value]"].FirstOrDefault();
            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;

            var userData = this.usersService.GetUsersData(sortColumn, sortColumnDirection, searchValue);

            recordsTotal = userData.Count();

            var data = userData.Skip(skip).Take(pageSize).ToList();
            var jsonData = new { draw, recordsFiltered = recordsTotal, recordsTotal, data };

            return this.Ok(jsonData);
        }
        catch (Exception e)
        {
            throw;
        }
    }
}

我注入了具有以下方法的 IUsersService:

public IEnumerable<ApplicationUser> GetUsersData(string sortColumn, string sortColumnDirection, string searchValue)
    {
        var users = this.usersRepository.All();
        var userData = from user in users select user;

        if (!(string.IsNullOrEmpty(sortColumn) && string.IsNullOrEmpty(sortColumnDirection)))
        {
            userData = userData.OrderBy(sortColumn + " " + sortColumnDirection);
        }

        if (!string.IsNullOrEmpty(searchValue))
        {
            userData = userData.Where(s => s.FirstName.Contains(searchValue)
                                || s.MiddleName.Contains(searchValue)
                                || s.LastName.Contains(searchValue)
                                || s.BirthDate.ToShortDateString().Contains(searchValue)
                                || s.Gender.ToString().Contains(searchValue)
                                || s.PhoneNumber.Contains(searchValue));
        }

        return userData;
    }

我的 Index.cshtml 文件如下:

@{
    this.ViewData["Title"] = "Home Page";
}

<link href="~/lib/datatables.net-bs5/dataTables.bootstrap5.min.css" rel="stylesheet" />

<div class="container-fluid">
    <br />
    <div style="width:90%; margin:0 auto;">
        <table id="usersTable" class="table table-striped table-bordered dt-responsive nowrap"
               width="100%" cellspacing="0">
            <thead>
                <tr>
                    <th>Id</th>
                    <th>@GlobalConstants.FirstName</th>
                    <th>@GlobalConstants.MiddleName</th>
                    <th>@GlobalConstants.LastName</th>
                    <th>@GlobalConstants.BirthDate</th>
                    <th>@GlobalConstants.Gender</th>
                    <th>@GlobalConstants.PhoneNumber</th>
                </tr>
            </thead>
        </table>
    </div>
</div>
@section Scripts
{
    <script src="~/lib/datatables.net/jquery.dataTables.min.js"></script>
    <script src="~/lib/datatables.net-bs5/dataTables.bootstrap5.min.js"></script>
    <script src="~/js/usersTable.js"></script>
}

我的usersTable.js包含以下代码:

$(document).ready(function () {
    $("#usersTable").DataTable({
        "processing": true,
        "serverSide": true,
        "filter": true,
        "ajax": {
            "url": "/api/Users/GetUsers",
            "type": "POST",
            "datatype": "json"
        },
        "columnDefs": [{
            "targets": [0],
            "visible": false,
            "searchable": false
        }],
        "columns": [
            { "data": "id", "name": "Id", "autoWidth": true },
            { "data": "firstName", "name": "First Name", "autoWidth": true },
            { "data": "middleName", "name": "Middle Name", "autoWidth": true },
            { "data": "lastName", "name": "Last Name", "autoWidth": true },
            { "data": "birthDate", "name": "Birth Date", "autoWidth": true },
            { "data": "gender", "name": "Gender", "autoWidth": true },
            { "data": "phoneNumber", "name": "Phone Number", "autoWidth": true },
        ]
    });
});

当我启动应用程序时,我收到以下错误: "DataTables 警告:table id=usersTable - Ajax 错误。有关此错误的详细信息,请参阅 http://datatables.net/tn/7". 错误状态代码为 400。 我尝试调试应用程序,但我注意到我在 ApiController 的 GetUsers() 方法开头的断点从未到达。我究竟做错了什么?我在不同的论坛中搜索了很多不同的解决方案,但似乎对我没有任何帮助。我对此很陌生,所以我可能遗漏了一些东西。请帮忙!

  1. 确保您的 API 路线正确且可访问

  2. 将此行放入您的 Razor 视图中:

    @Html.AntiForgeryToken()
    
  3. 将此配置添加到您的 startupprogram (.net 6) class

    services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
    
  4. 在 DataTable JS 配置中,添加此配置:

     "ajax": {
         "url": "/api/Users/GetUsers",
         "beforeSend": function (xhr) {
             xhr.setRequestHeader("XSRF-TOKEN",
                $('input:hidden[name="__RequestVerificationToken"]').val());
          },
          "type": "POST",
          "datatype": "json"
      },