.NET Core3.1 解决跨域问题 Startup的配置

废话不多说,直接上代码

跨域的代码在 #region 里

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.OpenApi.Models;

namespace Project.API
{
    public class Startup
    {
        private string MyAllowSpecificOrigins = "MyAllowSpecificOrigins";//这里也是跨域的东西

        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 void ConfigureServices(IServiceCollection services)
        {
            #region 跨域

            // services.AddCors(); 原本的配置

            // 新的配置,不限制跨域请求
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,

                    builder => builder.AllowAnyOrigin()

                    .WithMethods("GET", "POST", "HEAD", "PUT", "DELETE", "OPTIONS")

                    );

            });

            #endregion

            services.AddControllers();

            Register(services);

            services.AddOptions();

            
        }

        /// 
        /// 依赖注入
        /// 
        /// 
        private static void Register(IServiceCollection services)
        {


        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            #region 跨域

            /*
            app.UseCors(builder =>
            {
                builder.WithOrigins(GlobalContext.SystemConfig.AllowCorsSite.Split(',')).AllowAnyHeader().AllowAnyMethod().AllowCredentials();
            });
            */

            app.UseCors(MyAllowSpecificOrigins);

            #endregion

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();   

            app.UseRouting();

            app.UseAuthorization();

        }
    }
}

你可能感兴趣的:(.NET Core3.1 解决跨域问题 Startup的配置)