You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 5 Web应用集成DataTables.js时触发Incorrect Content-Type 500错误求助

问题根因

报错Incorrect Content-Type是因为后端代码通过Request.Form读取请求参数时,要求请求头的Content-Type必须为application/x-www-form-urlencoded或multipart/form-data,你当前的Datatable AJAX请求未配置正确的请求头和参数提交格式,导致触发该异常。另外你的代码中还存在多处拼写错误、路由不匹配的问题,也会导致请求失败。

解决方案

1. 修复前端Datatable配置

你的JS代码存在多处拼写错误,同时需要补充AJAX请求的Content-Type配置:

$(document).ready(function () {
$("#studentDatatable").DataTable({
    "processing": true,
    "serverSide": true, // 修复拼写错误:原severSide少了r
    "filter": true,
    "ajax": {
        "url": "/api/student",
        "type": "POST",
        "dataType": "json", // 修复大小写:原datatype改为标准写法dataType
        "contentType": "application/x-www-form-urlencoded; charset=UTF-8", // 新增表单提交的Content-Type
        "data": function (d) {
            return d; // 配置Datatable以表单格式提交内置参数
        }
    },
    "columnDefs": [{
        "targets": [0],
        "visible": false, // 修复拼写错误:原visable拼写错误
        "searchable": false
    }],
    "columns": [
        { "data": "Id", "name": "Id", "autoWidth": true },
        { "data": "FirstName", "name": "First Name", "autoWidth": true },
        { "data": "LastName", "name": "Last Name", "autoWidth": true },
        { "data": "Email", "name": "Email", "autoWidth": true }           
    ]
}); });

2. 修复后端路由匹配问题

你使用了[ApiController]特性,默认会把Action名称加入路由规则,当前GetStudents接口的实际访问地址为POST /api/Student/GetStudents,和前端配置的/api/student不匹配,需要修改Controller代码:

[HttpPost("")] // 新增空路由模板,直接匹配Controller级别的api/student路由
public IActionResult GetStudents()

同时修复排序逻辑的判断错误:

// 原判断逻辑错误:排序方向为空时才排序,改为排序方向不为空时执行排序
if(!string.IsNullOrEmpty(sortColumn) && !string.IsNullOrEmpty(sortColumnDirection))
{
    customerData = customerData.OrderBy(sortColumn + " " + sortColumnDirection); // 新增空格避免字段名和排序方向拼接错误
}

3. 可选优化方案(推荐)

如果不想用表单提交参数,也可以定义Datatable请求参数模型,通过[FromBody]接收JSON格式的参数,代码可维护性更高:

// 定义参数接收模型
public class DatatableRequest
{
    public int Draw { get; set; }
    public int Start { get; set; }
    public int Length { get; set; }
    public List<DatatableColumn> Columns { get; set; }
    public List<DatatableOrder> Order { get; set; }
    public DatatableSearch Search { get; set; }
}
// 配套定义Column、Order、Search类的结构即可
// Action修改为
[HttpPost("")]
public IActionResult GetStudents([FromBody] DatatableRequest request)

对应前端AJAX修改为提交JSON格式即可。


内容的提问来源于stack exchange,提问作者NerdyDriod

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 23:54:07