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

ASP.NET Core与Visual Studio 2022中AJAX请求404错误求助

AJAX调用失败排查请求(ASP.NET Core + Visual Studio 2022)

我已经花了好几个小时查各种示例,但AJAX就是跑不起来。我用Visual Studio 2022和ASP.NET Core开发,下面是布局截图、相关代码,麻烦帮忙找出问题。

布局截图

布局截图

Create.cshtml底部代码

</script>
@section scripts {
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
    <script>
        $(document).ready(function () {
            alert("Okay");
            $.ajax({
                type: "POST",
                url: "http://localhost:7103/HomeCascading/Get_3Data",
                dataType: "json",
                data: { name: "Smith" },
                success: function (res) {
                    alert("_a_Success_ " +res)
                },
                error: function (res) {
                    alert("_b_err_=_ " +res.d+" " +res)
                }
            });
        });
    </script>
}

Program.cs部分代码

// Add services to the container.
builder.Services.AddRazorPages();
builder.Services.AddControllersWithViews();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();
app.UseAuthentication();;

app.UseAuthorization();

app.MapAreaControllerRoute(
    name: "default",
    areaName: "YourIrrFields",
    pattern: "{controller=HomeCascading}/{action=Create}");

app.MapRazorPages();

app.Run();

后端目标方法

[HttpPost]
public IActionResult Get_3Data(string name)
{
    string stTest = name;
    return Ok(name);
}

排查方向与修复建议

  1. 路由区域匹配错误
    你的控制器属于YourIrrFields区域,但AJAX请求URL未包含区域路径,导致路由无法匹配。不要硬编码URL,改用Url.Action自动生成正确路径:

    url: '@Url.Action("Get_3Data", "HomeCascading", new { area = "YourIrrFields" })'
    
  2. 跨域与端口问题
    硬编码localhost:7103如果和前端页面运行端口不一致,会触发跨域拦截。使用相对路径或Url.Action可以避免这个问题,若确实需要跨域,需在后端配置CORS规则。

  3. 参数绑定与请求格式
    POST请求的参数绑定建议明确指定来源,给后端参数添加[FromForm]特性:

    [HttpPost]
    public IActionResult Get_3Data([FromForm] string name)
    {
        string stTest = name;
        return Ok(name);
    }
    

    同时可在AJAX配置里显式声明contentType(jQuery默认值为application/x-www-form-urlencoded,显式声明更稳妥):

    contentType: "application/x-www-form-urlencoded",
    
  4. 错误处理优化
    原错误回调里的res.d是旧ASP.NET WebForms的写法,ASP.NET Core中应通过xhr对象获取错误详情:

    error: function (xhr, status, error) {
        alert("错误状态:" + status + "\n错误信息:" + error + "\n响应内容:" + xhr.responseText);
    }
    

    这样能直接看到具体错误原因(如404路由未找到、500服务器内部错误等)。

  5. 控制器区域特性缺失
    确认HomeCascadingController类上添加了[Area("YourIrrFields")]特性,否则路由系统无法识别该控制器属于指定区域。

  6. 依赖版本兼容性
    使用的jQuery 3.2.1版本过旧,可能和ASP.NET Core环境存在兼容性问题,建议升级到较新的稳定版(如3.6.4)。

  7. 中间件语法错误
    Program.cs中app.UseAuthentication();;多了一个分号,虽不影响运行,但建议修正为app.UseAuthentication();。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:07:06