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

.NET Core 6配置Cors后Jquery上传文件仍报跨域错误

解决方案:.NET Core 6 跨域文件上传 CORS 错误修复

你的核心问题是Program.cs 未正确加载 Startup.cs 中的服务配置,导致你定义的 CORS 策略根本没有被注册到系统中。以下是具体修复步骤:

1. 修复服务配置加载问题

.NET Core 6 默认采用 Top-level Statements 模式,若你保留了传统的 Startup.cs 文件,需要在 Program.cs 中显式指定使用它,否则 Startup.cs 里的所有服务配置(包括 CORS)都会被忽略。

修改后的 Program.cs:

using System.Globalization;
var builder = WebApplication.CreateBuilder(args);

// 关键:启用Startup.cs的服务配置,替换原有的builder.Services.AddControllersWithViews();
builder.WebHost.UseStartup<Startup>();

var app = builder.Build();
// 后续中间件配置保持不变
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    app.UseHsts();
}
app.UseDeveloperExceptionPage();

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

app.UseRouting();
app.UseCors("NUXT"); // 位置正确:必须在UseRouting之后、UseAuthorization之前
app.UseAuthorization();

var localizationOptions = new RequestLocalizationOptions()
{
    DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("fa-IR"),
    SupportedCultures = new List<CultureInfo> { new CultureInfo("fa-IR") }
};
app.UseRequestLocalization(localizationOptions);    

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}");

app.Run();

2. 优化 CORS 策略(可选但建议)

如果你的文件上传需要携带凭证(如 Cookie、JWT),需要在 Startup.cs 的 CORS 策略中添加 .AllowCredentials(),同时前端请求要开启凭证传递:

修改 Startup.cs 中的 CORS 配置:

services.AddCors(options =>
{
    options.AddPolicy("NUXT",
                    builder =>
                    {
                        // 开发环境可使用AllowAnyOrigin,生产环境建议指定具体域名
                        builder.AllowAnyOrigin()
                               .AllowAnyHeader()
                               .AllowAnyMethod()
                               .AllowCredentials(); // 新增:允许携带凭证
                    });
});

3. 前端 JQuery 上传请求配置

确保前端请求正确设置文件上传参数,若需要凭证则开启 withCredentials:

var formData = new FormData();
formData.append("file", $("#fileInput")[0].files[0]);

$.ajax({
    url: "/api/YourUploadController/Upload",
    type: "POST",
    processData: false,
    contentType: false,
    data: formData,
    xhrFields: {
        withCredentials: true // 对应后端的AllowCredentials配置
    },
    success: function(res) {
        console.log("上传成功");
    },
    error: function(xhr) {
        console.error(xhr.responseText);
    }
});

关键注意事项

  • 中间件顺序:UseCors 必须放在 UseRouting 之后、UseAuthorization 之前,你的现有代码中顺序是正确的。
  • 生产环境安全:不要在生产环境使用 AllowAnyOrigin(),应替换为具体的前端域名,例如 builder.WithOrigins("https://your-frontend.com")。
  • 重复服务注册:避免在 Program.cs 和 Startup.cs 中重复注册 AddControllersWithViews(),否则会覆盖之前的配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 00:06:18