ASP.NET Core中设置跨域

1.添加NuGet包"Microsoft.AspNetCore.Cors"

2.appsettings.json中配置可跨域的站点

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AppSetting": {
    "Cores": "https://localhost:5001,http://localhost:5000,http://172.18.5.68:5200"
  },
  "AllowedHosts": "*",

3.Startup中配置

     readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
 public void ConfigureServices(IServiceCollection services)
 {
            #region 跨域
            var urls = Configuration["AppSetting:Cores"].Split(',');
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins(urls);
                                      //builder.AllowAnyOrigin(); //允许所有站点跨域请求
                                  });
            });
            #endregion
            services.AddControllersWithViews();
}


   public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
                #region 跨域
                app.UseCors(MyAllowSpecificOrigins);
                #endregion

            app.UseAuthorization();


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

参考:https://docs.microsoft.com/zh-cn/aspnet/core/security/cors?view=aspnetcore-3.1

你可能感兴趣的:(ASP.NET,Core)