asp.net webapi 跨域及 netcore3.1 跨域处理方式

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

跨域,跨域,之前用的挺稳定的,今天突然出问题了,哎,搞到最后是浏览器把我的站点设为非安全站点造成的,奶奶个腿,换个浏览器就又不存在跨域问题了...

那么这也就是说,代码是没问题的

索性记录下来吧

asp.net 方法1

1、引用NuGet的第三方包:Microsoft.AspNet.WebApi.Cors

 2、在 /App_Start/WebApiConfig.cs 中添加代码:

config.EnableCors();

如下:

        public static void Register(HttpConfiguration config)
        {
            config.EnableCors();
            //EnableCrossSiteRequests(config);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }

然后在我们的控制器上增加如下标识:

    [EnableCors(origins: "*", headers: "*", methods: "GET,POST,PUT,DELETE")]

如下:

    /// <summary>
    /// 2g电池 NB5311相关
    /// </summary>
    [RoutePrefix("api/Battery2gTcpip")]
    [EnableCors(origins: "*", headers: "*", methods: "GET,POST,PUT,DELETE")]
    //[ApiActionAuth]
    public class Battery2gTcpipController : ApiController

asp.net 方法2

1、只需在 /App_Start/WebApiConfig.cs 中添加代码:

        private static void EnableCrossSiteRequests(HttpConfiguration config)
        {
            //对所有的请求来源没有任何限制
            var cors = new EnableCorsAttribute(
             origins: "*",
             headers: "*",
             methods: "*"
             );
            config.EnableCors(cors);
        }

2、引用这个方法即可:

        public static void Register(HttpConfiguration config)
        {
           // config.EnableCors();
            EnableCrossSiteRequests(config);
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }


        private static void EnableCrossSiteRequests(HttpConfiguration config)
        {
            //对所有的请求来源没有任何限制
            var cors = new EnableCorsAttribute(
             origins: "*",
             headers: "*",
             methods: "*"
             );
            config.EnableCors(cors);
        }

上述两种方式为asp.net的方法

netcore3.1的方法如下

1.安装程序CORS程序包

Install-Package Microsoft.AspNetCore.Mvc.Cors

这个包初始化项目时一般都会自带。

2.配置CORS服务

在 Startup类,ConfigureServices方法里,添加如下代码:

  readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins("http://localhost:8080",
                                                          "http://localhost:8081", "http://xx.com", "https://xx.com/5awebsite");
                                  });
            });
            services.AddControllers();

全文如下:

public IConfiguration Configuration { get; }
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder =>
                                  {
                                      builder.WithOrigins("http://localhost:8080",
                                                          "http://localhost:8081");
                                  });
            });
            services.AddControllers();
            //改变netCOre默认驼峰风格,返回的JOSN和实例类一致
            //services.AddControllers().AddNewtonsoftJson(options =>
            //{
            //    options.SerializerSettings.ContractResolver = new DefaultContractResolver();
            //});
            //选项模式
            services.Configure<WuAnModels.Document.FileOptions>(Configuration.GetSection("FileOptions"));
            services.Configure<WuAnModels.Document.IsDevelopOptions>(Configuration.GetSection("IsDevelopOptions")); 
            services.Configure<WuAnModels.Document.PayCenterSetting>(Configuration.GetSection("PayCenterSetting"));
            WxPayHelper.Init(Configuration.GetSection("WxPaymentSettings"));
            #region 注册SQLSERVER
            services.AddDbContext<WuAnDBTestContext>(options =>
                 options.UseSqlServer(Configuration.GetConnectionString("WuAnDBContext")));
            #endregion

            #region JWT
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata = false;
                x.SaveToken = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(TokenManagementModel.Secret)),
                    ValidIssuer = TokenManagementModel.Issuer,
                    ValidAudience = TokenManagementModel.Audience,
                    ValidateIssuer = false,
                    ValidateAudience = false
                };
            });
            #endregion

            #region Swagger
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "Swagger管理平台", Version = "V1" });
                c.SwaggerDoc("v2", new OpenApiInfo { Title = "管理平台改造工程", Version = "V2" });
                c.DocInclusionPredicate((docName, apiDesc) => apiDesc.GroupName == docName.ToUpper());
                var basePath = Path.GetDirectoryName(typeof(Program).Assembly.Location);
                var xmlPath = Path.Combine(basePath, "WuAnApi.xml");
                c.IncludeXmlComments(xmlPath);
                #region Jwt
                c.OperationFilter<AddResponseHeadersFilter>();
                c.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                c.OperationFilter<SecurityRequirementsOperationFilter>();
                c.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传递)直接在下面框中输入Bearer {token}(注意两者之间是一个空格) "",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });


                #endregion
            });
            #endregion

            #region 注册自定义服务
            //services.AddScoped<IWuAnTest, WuAnTestService>();
            services.AddScoped<ISysDocument, SysDocumentService>();
            services.AddScoped<ISysGroupAccount,SysGroupAccountService>();
            services.AddScoped<IGroupBuy, GroupBuyService>();
            services.AddScoped<IToken, TokenService>();
            services.AddScoped<IFinanceWithdrawApp, FinanceWithdrawAppService>();
            services.AddScoped<ISysSettings, SysSettingsService>();
            services.AddScoped<ITeamLeaderApproval, TeamLeaderApprovalService>();
            services.AddScoped<ITeamMemberInfo, TeamMemberInfoService>();
            //services.AddScoped<IBatteryInfo, BatteryService>();

            #region 老平台改造
            services.AddScoped<ISysGroupInfos, SysGroupInfoService>();
            services.AddScoped<IHardware, HardwareService>();
            #endregion
            #endregion
        }
View Code

最后在 Configure 中注册如下:

 //允许跨域
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("Content-Disposition"));

  //注册跨域
            app.UseCors(MyAllowSpecificOrigins);

全文如下:

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            //允许跨域
            app.UseCors(builder => builder.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod().WithExposedHeaders("Content-Disposition"));
            //注册异常中间件
            app.UseMiddleware<ExceptionMiddlewares>();
            #region 启用Swagger中间件
            // 启用Swagger中间件
            app.UseSwagger(c => c.RouteTemplate = "/swagger/{documentName}/swagger.json");
            // 配置SwaggerUI
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint($"/swagger/v1/swagger.json", "V1");
                c.SwaggerEndpoint($"/swagger/v2/swagger.json", "V2");
            });
            #endregion
            app.UseAuthentication();

            app.UseHttpsRedirection();

            app.UseRouting();
            //注册跨域
            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthorization();

            //启动日志
            EFLoggerHelper.Register();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

主要是 app.UseCors("cors");这句代码,需要注意的是必须放在 UseMvc 之前,且策略名称必须是已经定义的

短短几行代码即可解决跨域问题。奥利给....

@天才卧龙的博客

原文地址:https://www.cnblogs.com/chenwolong/p/cors.html