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

AJAX请求ASP.NET Core MVC控制器返回404错误求助

AJAX调用ASP.NET Core MVC控制器返回404问题解决

问题场景

通过AJAX向ASP.NET Core MVC控制器传递对象,数据本身无误,但请求返回404错误,无法匹配到路由。

相关代码

JavaScript AJAX代码

$('#employee_table tbody').on('click', '.editLink', function () {
    var data = employee_table.row($(this).parents('tr')).data();
    $.ajax({
        type: 'POST',
        data: data,
        url: '/Employee',
        contentType: 'application/json',
        dataType: 'json'
    });
});

控制器代码

public class EmployeeController : Controller
{
    private readonly IEmployeeService _iEmployeeService;
    private readonly ICommentService _iCommentService;

    public EmployeeController(IEmployeeService _iemployeeService, ICommentService _icommentService)
    {
        this._iEmployeeService = _iemployeeService;
        _iCommentService = _icommentService;
    }

    public IActionResult Employee(object obj)
    {
        EmployeeDTO emp = (EmployeeDTO)obj;
        EmployeeDetailViewModel employeeDetailViewModel = new(emp);

        return View(employeeDetailViewModel);
    }
}

控制台错误信息

Failed to load resource: the server responded with a status of 404 () Employee:1

错误原因分析

  1. Action未指定请求方式:默认情况下ASP.NET Core MVC的Action仅接受GET请求,AJAX使用POST方法,导致无法匹配对应Action,返回404。
  2. URL路径错误:默认路由模板为{controller=Home}/{action=Index}/{id?},控制器是EmployeeController、Action是Employee时,正确请求路径应为/Employee/Employee,而非/Employee(后者会匹配EmployeeController的默认Action,你这里未定义Index Action)。
  3. AJAX数据格式不匹配:设置了contentType: 'application/json',但直接传入JS对象会被jQuery自动转为表单编码格式,后端无法解析JSON数据。
  4. 参数绑定问题:用object obj接收参数后强制转EmployeeDTO,模型绑定无法将JSON数据正确绑定到object类型,后续转换也会出错。
  5. 响应类型不匹配:AJAX期望JSON响应(dataType: 'json'),但Action返回的是HTML视图,请求完成后会解析失败。

修复方案

1. 给Action添加POST请求特性

修改控制器Action,明确接受POST请求,并优化参数类型:

[HttpPost]
public IActionResult Employee(EmployeeDTO emp)
{
    EmployeeDetailViewModel employeeDetailViewModel = new(emp);
    // 若需返回JSON,替换为return Json(employeeDetailViewModel);
    return View(employeeDetailViewModel);
}

2. 修正AJAX请求URL

使用Url.Action生成可靠路径(避免硬编码错误):

<script>
    const employeeActionUrl = '@Url.Action("Employee", "Employee")';
    $('#employee_table tbody').on('click', '.editLink', function () {
        var data = employee_table.row($(this).parents('tr')).data();
        $.ajax({
            type: 'POST',
            data: JSON.stringify(data),
            url: employeeActionUrl,
            contentType: 'application/json',
            dataType: 'html' // 返回视图时用html,返回JSON则保持json
        });
    });
</script>

3. 修正AJAX数据格式

通过JSON.stringify()将JS对象转为JSON字符串,匹配contentType: 'application/json'的要求。

4. 调整响应类型匹配

如果需要返回JSON数据,修改控制器Action返回JsonResult;如果返回页面内容,将AJAX的dataType设为'html'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 14:59:55