.NET CORE如何配置跨域

1. 安装Microsoft.AspNetCore.Cors (Nuget)

2. Startup.cs做配置

 public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            //Config Mvc
            services.AddMvc();

            //Config Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info { Title = "Water Cube API", Version = "v1" });
                // Set the comments path for the Swagger JSON and UI.
                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                c.IncludeXmlComments(xmlPath);
            });

            //Config Cors          
            services.AddCors();

            services.AddCors(options =>
            {
                options.AddPolicy("WaterCubeCorsPolicy",
                    corsBuilder => corsBuilder.AllowAnyOrigin()
                                              .AllowAnyMethod()
                                              .AllowAnyHeader()
                                              .AllowCredentials());
            });


            //Config Autofac
            var builder = ContainerManager.Builder;
            builder.Populate(services);
            return new AutofacServiceProvider(builder.Build());            
        }
 public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
        {            
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            ////Config NLog
            loggerFactory.AddNLog();
            app.AddNLogWeb();
            loggerFactory.ConfigureNLog("nlog.config");

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Water Cube API V1");
            });

            //Config Cors's policy
            app.UseCors("WaterCubeCorsPolicy");
        }

3. 控制器配置CorsPolicy

.NET CORE如何配置跨域_第1张图片

你可能感兴趣的:(.NET CORE如何配置跨域)