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

如何在.NET Core 3.1的控制器/基础控制器中获取AJAX请求的dataType值

前提说明

jQuery AJAX的dataType是前端框架内部使用的配置参数,默认不会作为请求内容主动发送给服务端,所以服务端无法直接从原生HTTP请求中读取该值,可通过以下两种方案实现获取:


方案1:前端手动透传(最准确,推荐)

修改前端AJAX代码,将dataType的值通过自定义请求头或者URL参数透传给后端,前端代码示例:

$.ajax({
    type: "POST",
    url: "/Customers/GetAll",
    contentType: "application/json",
    dataType: "json",
    // 新增自定义请求头传递dataType值
    headers: {
        "X-Jquery-DataType": "json"
    },
    success: function(response) {
        console.log(response);
    },
    error: function(response) {
        console.log(response);
    }
});

后端在Action或基础控制器中获取方式:

public IActionResult GetAll()
{
    // 直接从请求头中读取透传的值,基础控制器中也可以用完全相同的逻辑获取
    string jqueryDataType = Request.Headers["X-Jquery-DataType"].FirstOrDefault();
    // 业务逻辑...
}

方案2:通过Accept头间接推断(无需修改前端,仅适用于未自定义Accept配置的场景)

如果你没有手动修改AJAX请求的accept配置,jQuery会自动根据dataType的值设置对应的Accept请求头,对应关系如下:

  • dataType: "json" → Accept头包含application/json
  • dataType: "xml" → Accept头包含application/xml
  • dataType: "text" → Accept头包含text/plain

后端获取判断逻辑:

public IActionResult GetAll()
{
    // 获取请求Accept头
    var acceptHeader = Request.Headers.Accept.FirstOrDefault();
    // 推断对应的dataType值
    string dataType = acceptHeader switch
    {
        string s when s.Contains("application/json") => "json",
        string s when s.Contains("application/xml") => "xml",
        string s when s.Contains("text/plain") => "text",
        _ => "default"
    };
    // 业务逻辑...
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:15:08