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

C# Web API部署服务器后React前端访问出现CORS错误怎么解决?

C# Web API部署到服务器后跨域(CORS)错误问题

(我的英语不太好)您好,我遇到了如下问题:将C# Web API部署到服务器后,我从本地主设备访问React站点时会抛出CORS错误;若在本地同时运行Web API和React项目则功能正常,但由于团队多人协作需要,必须使用服务器部署的版本。
希望能得到大家的帮助。


报错信息

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://ServerIP/api/user. (Reason: CORS request did not succeed).

后续在Chrome浏览器运行React项目时,报错变为net::ERR_CERT_AUTHORITY_INVALID。


已尝试的解决方案

  • 在ConfigureServices中添加CORS默认配置:
public static void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddDefaultPolicy(builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()));
}
  • 调整端点配置:
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
        name: "default",
        pattern: "{controller}/{action=Index}/{id?}"
    );
    endpoints.MapControllers();
});
  • 给控制器类添加EnableCors特性:
[EnableCors("*", "*", "*")]

相关代码

React axios实例封装

import Axios from 'axios'

const WorkifyAPI = Axios.create({
    baseURL: 'https://ServerIP:42069/api'
})

export default WorkifyAPI

接口服务代码

import http from '../WorkifyAPI'
const GetallWorkouts = (userID: string) => {
    return http.get(`/user/${userID}/WorkoutData`)
}

export default {
    GetallWorkouts,
}

补充:Startup.cs完整代码

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public static void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();

        services.AddControllers();

    }

    public static void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowCredentials());

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(
                name: "default",
                pattern: "{controller}/{action=Index}/{id?}");
            endpoints.MapControllers();
        });
    }
}

排查进展

根据报错信息可判定问题和SSL证书有关,后续将从该方向进行排查。

开发者工具请求截图

开发者工具请求截图


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.16 07:06:07