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

ASP.NET Core对接Angular前端出现CORS错误无法接收后端数据如何解决

问题修复方案

    1. 修正Origin地址的末尾斜杠
      修改Configure方法里的UseCors配置,把"http://localhost:4200/"末尾的斜杠删除,ASP.NET Core的CORS Origin匹配为严格校验,多余的斜杠会导致匹配失败:
    app.UseCors(options =>
      options.WithOrigins("http://localhost:4200")
      .AllowAnyMethod()
      .AllowAnyHeader());
    
    1. 调整CORS中间件的顺序
      ASP.NET Core 3.0+的中间件执行顺序有严格要求,UseCors必须放在UseRouting之后、UseEndpoints之前,你当前把UseCors放在了最开头,无法和路由系统匹配导致不生效,调整后的完整配置如下:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            app.UseHsts();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        if (!env.IsDevelopment())
        {
            app.UseSpaStaticFiles();
        }
    
        app.UseRouting();
    
        // 修正位置后的CORS中间件
        app.UseCors(options =>
        options.WithOrigins("http://localhost:4200")
        .AllowAnyMethod()
        .AllowAnyHeader());
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}")
            // 全局为控制器端点启用CORS
            .RequireCors();
        });
    
        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";
            if (env.IsDevelopment())
            {
                spa.UseAngularCliServer(npmScript: "start");
            }
        });
    }
    
    1. 可选优化:如果后续需要携带跨域Cookie等凭证,可在CORS配置末尾加上.AllowCredentials()。

修改完成后重启后端服务即可生效。你直接在浏览器访问API能拿到数据是因为直接访问不属于跨域请求,不会触发CORS校验,只有前端异步请求才会触发预检和CORS规则校验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 01:54:05