首页 > 解决方案 > Asp.net Core:跨域请求被阻止

问题描述

我使用 react 作为前端,asp.net 核心作为后端。我正在为 API 请求使用 fetch API,但我在浏览器控制台上收到 Cors 错误消息:跨域请求被阻止:同源策略不允许在 https://localhost:44316/api/auth/register 读取远程资源。(原因:CORS 请求未成功)。

我的 ConfigureServices 方法是:

public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy("myPolicy", builder =>
                {
                    builder.WithOrigins("http://localhost:3000")
                            .AllowAnyHeader()
                            .AllowAnyMethod()
                            .AllowCredentials();
                });
            });
            services.AddSignalR();
            services.AddDbContext<UserContext>(options => options.UseSqlServer(Configuration.GetConnectionString(name: "Default")));
            services.AddControllers();
            services.AddScoped<IUserRepository, UserRepository>();
            services.AddScoped<IJwtHelper, JwtHelper>();
        }

而配置方法是:

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

            app.UseRouting();

            app.UseCors("myPolicy");

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                endpoints.MapHub<ChatHub>("/chat");
            });
        }

在反应中,我创建了一个表单提交事件,它看起来像:

const submitRegisterForm = async (e) => {
    e.preventDefault();
    await fetch(
      "https://localhost:44316/api/auth/register",{
        method: 'POST',
        headers: {"Content-Type": "application/json"},
        body: JSON.stringify({
          name,
          email,
          password,
          role,
        })
      });

    setRedirectTo(true);
  };

这是我在浏览器网络选项卡中得到的输出:

在此处输入图像描述

标签: reactjsasp.net-corefetch-api

解决方案


在您的 ConfigureServices 方法中尝试如下

services.AddCors(options =>
            {
                options.AddPolicy("ClientPermission", policy =>
                {
                    policy.AllowAnyHeader()
                        .AllowAnyMethod()
                        .SetIsOriginAllowed(_ => true)
                        .AllowCredentials();
                });
            });

并在您的配置方法中

app.UseCors("ClientPermission");

推荐阅读