首页 > 解决方案 > 为什么我在从 .net 核心控制器调用 ajax 数据表 api 时不断收到 400 错误?

问题描述

cmjobprogress.js

    var JobdataTable;

$(document).ready(function () {
    loadJobDataTable();
});

function loadJobDataTable() {
    JobdataTable = $('#JobtblData').DataTable({
        "ajax": {
            "url": "/Admin/CMJobProgress/GetAll"
        },
        "columns": [
            { "data": "job_number" },
            { "data": "assign_from" },
            { "data": "assign)to" },
            { "data": "date_assign" },
            { "data": "job_action" },
            { "data": "remarks" },
            { "data": "type" },
            { "data": "division" }
        ]

    })
}

CMJobProgressController.cs

#region API Calls
        [ValidateAntiForgeryToken]
       [HttpGet]
       public IActionResult GetAll()
        {
            var allObj = _unitOfWork.cmJobProg.GetALL(j => j.JobNumber=="19950232"); 

            return Json(new { data = allObj });
        }

#endregion

索引.cshtml

@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">Job Action</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="cmd.html">Home</a></li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
        <div class="row mb-2">
            <div class="col-6 text-right">
            </div>
            <div class="col-6 text-right">
                <a class="btn btn-primary"><i class="fas fa-plus"></i> &nbsp; Create New Job</a>
            </div>
        </div>

    </div><!-- /.container-fluid -->
</div>

<section class="content">
    <div class="container-fluid">
        <div class="p-4 border rounded">
            <table id="JobtblData" class="table table-striped table-bordered" style="width:100%">
                <thead class="thead-dark">
                    <tr class="table-info">
                        <th>Job Number</th>
                        <th>Assign From</th>
                        <th>Assign To</th>
                        <th>Date Assign</th>
                        <th>Job Action</th>
                        <th>Remarks</th>
                        <th>Type</th>
                        <th>Division</th>


                    </tr>
                </thead>
            </table>
        </div>
    </div>
</section>


@section Scripts{

    <script src="~/js/cmjobprogress.js"></script>
}

CMJobProgress.cs

namespace LXG.Models
{
    [Table("CMJOBPROG", Schema = "LASIS")]
    public class CMJobProgress
    {
        [Required]
        [MaxLength(8)]
        [Display(Name = "Job Number")]
        [Column("JOB_NUMBER")]
        public string JobNumber { get; set; }

        [Display(Name = "Assign From")]
        [MaxLength(22)]
        [Column("ASSIGN_FROM")]
        public string AssignFrom { get; set; }

        [Display(Name = "Assign To")]
        [MaxLength(22)]
        [Column("ASSIGN_TO")]
        public string AssignTo { get; set; }

        [Column("DATE_ASSIGN")]
        public DateTime DateAssign { get; set; }

        [Display(Name = "Job Action")]
        [Range(0, 999)]
        [Column("JOB_ACTION")]
        public string JobAction { get; set; }

        [Display(Name = "Remarks")]
        [MaxLength(500)]
        [Column("REMARKS")]
        public string Remarks { get; set; }

        [Display(Name = "Job Type")]
        [Required]
        [MaxLength(2)]
        [Column("TYPE")]
        public string Type { get; set; }

        [MaxLength(2)]
        [Column("DIVISION")]
        public string Division { get; set; }

    }
}

ApplicationDbContext.cs

namespace LXG.DataAccess.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseOracle(@"User Id=xxxxx;Password=xxxxx;Data Source=xx.xx.xx.xx:xxxx/xxxxx;");

            }
        }

       
        public DbSet<CMJobProgress> CMJOBPROG { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {


            modelBuilder.Entity<CMJobProgress>(builder =>
            {
                builder.HasNoKey();
                builder.ToTable("CMJOBPROG");
            });
        }
    }
}

我得到的错误:

DataTables 警告:表 id=JobtblData - Ajax 错误。有关此错误的更多信息,请参阅http://datatables.net/tn/7

请求 URL:https://localhost:44382/Admin/CMJobProgress/GetAll?_=1602720362984 请求方法:GET 状态码:400 远程地址:[::1]:44382 推荐人策略:strict-origin-when-cross-origin

有人可以帮我吗?

标签: javascriptajaxasp.net-core.net-core

解决方案


根据您的控制器代码,我发现您已为您的 api 调用启用了 ValidateAntiForgeryToken。

但是您的数据表的 ajax 调用不会将 AntiForgery 令牌作为标头发送到 api ,因此它会显示 400 错误。

要解决此问题,您应该@Html.AntiForgeryToken()在视图中添加 并修改 cmjobprogress.js 以获取令牌并将其发送到 api。

更多细节,您可以参考以下代码:

看法:

@{

    Layout = "~/Views/Shared/_Layout.cshtml";
}

<div class="content-header">
    <div class="container-fluid">
        <div class="row mb-2">
            <div class="col-sm-6">
                <h1 class="m-0 text-dark">Job Action</h1>
            </div><!-- /.col -->
            <div class="col-sm-6">
                <ol class="breadcrumb float-sm-right">
                    <li class="breadcrumb-item"><a href="cmd.html">Home</a></li>
                </ol>
            </div><!-- /.col -->
        </div><!-- /.row -->
        <div class="row mb-2">
            <div class="col-6 text-right">
            </div>
            <div class="col-6 text-right">
                <a class="btn btn-primary"><i class="fas fa-plus"></i> &nbsp; Create New Job</a>
            </div>
        </div>

    </div><!-- /.container-fluid -->
</div>

<section class="content">
    <div class="container-fluid">
        <div class="p-4 border rounded">
            <table id="JobtblData" class="table table-striped table-bordered" style="width:100%">
                <thead class="thead-dark">
                    <tr class="table-info">
                        <th>Job Number</th>
                        <th>Assign From</th>
                        <th>Assign To</th>
                        <th>Date Assign</th>
                        <th>Job Action</th>
                        <th>Remarks</th>
                        <th>Type</th>
                        <th>Division</th>


                    </tr>
                </thead>
            </table>
        </div>
    </div>
</section>
@Html.AntiForgeryToken()

@section Scripts{

    <script src="~/js/cmjobprogress.js"></script>
}

cmjobprogress.js:

<script>

    var JobdataTable;

    $(document).ready(function () {
        loadJobDataTable();
    });

    function loadJobDataTable() {
        JobdataTable = $('#JobtblData').DataTable({
            "ajax": {
                "url": "/Admin/CMJobProgress/GetAll"
                'beforeSend': function (request) {
                    request.setRequestHeader("RequestVerificationToken", document.getElementsByName('__RequestVerificationToken')[0].value);
                }
             },
            "columns": [
                { "data": "job_number" },
                { "data": "assign_from" },
                { "data": "assign)to" },
                { "data": "date_assign" },
                { "data": "job_action" },
                { "data": "remarks" },
                { "data": "type" },
                { "data": "division" }
            ]

        })
    }
</script>

推荐阅读