From 4690486b9cb5cb24cd54bf05cecce7e71b49f681 Mon Sep 17 00:00:00 2001
From: bicijinlian <bicijinlian@163.com>
Date: Wed, 28 Apr 2021 18:45:49 +0800
Subject: [PATCH] =?UTF-8?q?=E6=9B=B4=E6=96=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

---
 CorsServer/CorsServer.WebApi31/ApiConst.cs    |  16 ++
 .../CorsServer.WebApi31/Config/CorsOption.cs  |   5 -
 .../Controllers/CorsController.cs             |   6 +-
 CorsServer/CorsServer.WebApi31/Startup.cs     | 207 ++++++++++++++++--
 .../CorsServer.WebApi31/appsettings.json      |   9 +-
 5 files changed, 211 insertions(+), 32 deletions(-)
 create mode 100644 CorsServer/CorsServer.WebApi31/ApiConst.cs

diff --git a/CorsServer/CorsServer.WebApi31/ApiConst.cs b/CorsServer/CorsServer.WebApi31/ApiConst.cs
new file mode 100644
index 0000000..a4b16ea
--- /dev/null
+++ b/CorsServer/CorsServer.WebApi31/ApiConst.cs
@@ -0,0 +1,16 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Threading.Tasks;
+
+namespace CorsServer.WebApi31
+{
+    public class ApiConst
+    {
+    }
+
+    public class CorsPolicyNameConst
+    {
+        public const string DefaultPolicyName = "AllowAll";
+    }
+}
diff --git a/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs b/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs
index 4ccd71e..f818116 100644
--- a/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs
+++ b/CorsServer/CorsServer.WebApi31/Config/CorsOption.cs
@@ -7,11 +7,6 @@ namespace CorsServer.WebApi31
 {
     public class CorsOption
     {
-        /// <summary>
-        /// 策略名称
-        /// </summary>
-        public string PolicyName { get; set; }
-
         /// <summary>
         /// 允许跨域的域名列表
         /// </summary>
diff --git a/CorsServer/CorsServer.WebApi31/Controllers/CorsController.cs b/CorsServer/CorsServer.WebApi31/Controllers/CorsController.cs
index 3d22b91..30aeffd 100644
--- a/CorsServer/CorsServer.WebApi31/Controllers/CorsController.cs
+++ b/CorsServer/CorsServer.WebApi31/Controllers/CorsController.cs
@@ -14,8 +14,7 @@ namespace CorsServer.WebApi31.Controllers
     public class CorsController : ControllerBase
     {
         public CorsController()
-        { 
-        
+        {
         }
 
         [HttpGet]
@@ -26,9 +25,10 @@ namespace CorsServer.WebApi31.Controllers
 
             return Ok(data);
         }
+
         [HttpGet]
         [HttpOptions]
-        [EnableCors(Startup.CorsName)]
+        [EnableCors(CorsPolicyNameConst.DefaultPolicyName)]
         public IActionResult HasCors()
         {
             var data = new { Code = 0, Messge = "单独明确可以跨域" };
diff --git a/CorsServer/CorsServer.WebApi31/Startup.cs b/CorsServer/CorsServer.WebApi31/Startup.cs
index 787a33e..b19a6b2 100644
--- a/CorsServer/CorsServer.WebApi31/Startup.cs
+++ b/CorsServer/CorsServer.WebApi31/Startup.cs
@@ -10,13 +10,13 @@ using Microsoft.Extensions.Configuration;
 using Microsoft.Extensions.DependencyInjection;
 using Microsoft.Extensions.Hosting;
 using Microsoft.Extensions.Logging;
+using Microsoft.Extensions.Options;
 
 namespace CorsServer.WebApi31
 {
     public class Startup
     {
-        public const string CorsName = "Any";
-        public Startup(IConfiguration configuration)
+        public Startup(IConfiguration configuration,IHostEnvironment hostingEnvironment,IWebHostEnvironment webHostEnvironment)
         {
             Configuration = configuration;
         }
@@ -26,18 +26,19 @@ namespace CorsServer.WebApi31
         public void ConfigureServices(IServiceCollection services)
         {
             #region Config
-            services.Configure<CorsOption>();
+            services.Configure<CorsOption>(Configuration.GetSection("CORS"));
             #endregion
             #region  CORS
-            AddCors_1(services);
+            AddCors_Test(services);
             //AddCors_2(services);
             //AddCors_3(services);
             //AddCors_4(services);
+            //AddCors_5(services);
             #endregion
             services.AddControllers();
         }
 
-        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
+        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IOptionsSnapshot<CorsOption> corsOtionsSnapshot)
         {
             if (env.IsDevelopment())
             {
@@ -49,7 +50,7 @@ namespace CorsServer.WebApi31
 
             app.UseRouting();
 
-            app.UseCors(CorsName);
+            app.UseCors(CorsPolicyNameConst.DefaultPolicyName);
 
             app.UseAuthorization();
 
@@ -59,30 +60,171 @@ namespace CorsServer.WebApi31
             });
         }
 
-        private IServiceCollection AddCors_1(IServiceCollection services)
+        /// <summary>
+        /// ȫ��������˵��
+        /// </summary>
+        private IServiceCollection AddCors_Info(IServiceCollection services)
         {
             services.AddCors(setup =>
             {
-                setup.AddPolicy(CorsName, build =>
+                setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
                 {
                     build
+
+                    //������Դ
+                    .AllowAnyOrigin()                               //�����κ�������Դ
+                    //.WithOrigins()                                //����ָ��������Դ
+                    .SetIsOriginAllowed(_ => true)            //ʹ��Func<string bool> ί�з�����ȷ���Ƿ���������Դ����
+                    .SetIsOriginAllowedToAllowWildcardSubdomains()  //��������Դ��ʹ��ͨ���(*��) 
+
+                    //���󷽷�(POST GET PUT DELETE OPTIONS��)
+                    .AllowAnyMethod()                               //���������
+                    //.WithMethods()                                //����ָ������
+
+                    //����ͷ
+                    .AllowAnyHeader()                               //������������ͷ
+                    //.WithHeaders()                                //����ָ������ͷ
+                    
+                    //ƾ��
+                    .AllowCredentials()                             //����ƾ�ݣ�֤���а�������(cookies)��HTTP��֤Э��(HTTP authentication schemes)
+                    //.DisallowCredentials()                        //�ܾ�ƾ��
+
+                    //.WithExposedHeaders()                         //���ñ�¶���Զ�����Ӧͷ��Ĭ������£������ֻ�ᱩ¶Ĭ�ϵ���Ӧͷ��Ӧ�ã������Զ���Ӱ��ͷ���ᱩ¶��Ӧ�ó���
+                   ;
+
+                    /*�ر�˵����
+                      ���ڰ�ȫ���ǣ�.net core 2.1��ʼ, AllowAnyOrigin() �� AllowCredentials() ����ͬʱʹ��
+                      ���������
+                                1��ʹ��AllowCredentials()ʱ����.SetIsOriginAllowed(_ => true) ���� AllowAnyOrigin()
+                                2��ʹ��AllowCredentials()ʱ���� WithOrigins()ָ��������Դ(ʹ��SetIsOriginAllowedToAllowWildcardSubdomains()������ͨ���) ���� AllowAnyOrigin()
+                                3���Զ����м��
+                     */
+                });
+            });
+
+            return services;
+        }
+
+        /// <summary>
+        /// CORS �
+        /// </summary>
+        private IServiceCollection AddCors_Template(IServiceCollection services)
+        {
+            services.AddCors(setup =>
+            {
+                var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
+                setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
+                {
+                    build
+
+                    //������Դ
                     .AllowAnyOrigin()
+                    //.WithOrigins(corsOption.Origins.ToArray())
+                    //.SetIsOriginAllowed(_ => true)
+                    //.SetIsOriginAllowedToAllowWildcardSubdomains()
+
+                    //���󷽷�(POST GET PUT DELETE OPTIONS��)
                     .AllowAnyMethod()
+                    //.WithMethods(corsOption.Methods.ToArray())
+
+                    //����ͷ
                     .AllowAnyHeader()
-                    .WithExposedHeaders("x-custom-error");
+                    //.WithHeaders(corsOption.Headers.ToArray())
+
+                    //ƾ��
+                    //.AllowCredentials()
+                    //.DisallowCredentials()
+
+                    //.WithExposedHeaders()
+                   ;
                 });
             });
 
             return services;
         }
 
-        private IServiceCollection AddCors_2(IServiceCollection services)
+        /// <summary>
+        /// ����
+        /// </summary>
+        private IServiceCollection AddCors_Test(IServiceCollection services)
+        {
+            services.AddCors(setup =>
+            {
+                setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
+                {
+                    build
+
+                    //������Դ
+                    .AllowAnyOrigin()
+                    //.WithOrigins()
+                    //.SetIsOriginAllowed(_ => true)
+                    //.SetIsOriginAllowedToAllowWildcardSubdomains()
+
+                    //���󷽷�(POST GET PUT DELETE OPTIONS��)
+                    .AllowAnyMethod()
+                    //.WithMethods()
+
+                    //����ͷ
+                    .AllowAnyHeader()
+                    //.WithHeaders()
+
+                    //ƾ��
+                    //.AllowCredentials()
+                    //.DisallowCredentials()
+
+                    //.WithExposedHeaders()
+                   ;
+                });
+            });
+
+            return services;
+        }
+
+        private IServiceCollection AddCors_Single(IServiceCollection services)
+        {
+            services.AddCors(setup =>
+             {
+                 setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
+                 {
+                     build
+
+                     //������Դ
+                     .AllowAnyOrigin()
+                     //.WithOrigins()
+                     //.SetIsOriginAllowed(_ => true)
+                     //.SetIsOriginAllowedToAllowWildcardSubdomains()
+
+                     //���󷽷�(POST GET PUT DELETE OPTIONS��)
+                     //.AllowAnyMethod()
+                     //.WithMethods()
+
+                     //����ͷ
+                     //.AllowAnyHeader()
+                    //.WithHeaders()
+
+                    //ƾ��
+                    //.AllowCredentials()
+                    //.DisallowCredentials()
+
+                    //.WithExposedHeaders()
+                    ;
+                 });
+             });
+
+            return services;
+        }
+
+        private IServiceCollection AddCors_All(IServiceCollection services)
         {
             services.AddCors(setup =>
            {
-               setup.AddPolicy(CorsName, build =>
+               setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
                {
-                   build.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-custom-error");
+                   build
+                   .AllowAnyOrigin()
+                   .AllowAnyMethod()
+                   .AllowAnyHeader()
+                   ;
                });
            });
 
@@ -92,12 +234,17 @@ namespace CorsServer.WebApi31
         private IServiceCollection AddCors_3(IServiceCollection services)
         {
             services.AddCors(setup =>
-           {
-               setup.AddPolicy(CorsName, build =>
-               {
-                   build.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-custom-error");
-               });
-           });
+             {
+                 var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
+                 setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
+                 {
+                     build
+                     .WithOrigins(corsOption.Origins.ToArray())
+                     .WithMethods(corsOption.Methods.ToArray())
+                     .WithHeaders(corsOption.Headers.ToArray())
+                     .WithExposedHeaders(corsOption.ExposedHeaders.ToArray());
+                 });
+             });
 
             return services;
         }
@@ -106,12 +253,34 @@ namespace CorsServer.WebApi31
         {
             services.AddCors(setup =>
            {
-               setup.AddPolicy(CorsName, build =>
+               setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, build =>
                {
                    build.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().WithExposedHeaders("x-custom-error");
                });
            });
             return services;
         }
+
+        private IServiceCollection AddCors_5(IServiceCollection services)
+        {
+            services.AddCors(setup =>
+              {
+                  var corsOption = services.BuildServiceProvider().GetRequiredService<IOptionsSnapshot<CorsOption>>().Value;
+                  setup.AddPolicy(CorsPolicyNameConst.DefaultPolicyName, builder =>
+                  {
+                      builder
+                      ////.SetIsOriginAllowedToAllowWildcardSubdomains()
+                      .WithOrigins("http://localhost:5002")
+                      //.AllowAnyMethod()
+                      ////.WithMethods(corsOption.Methods.ToArray())
+                      //.AllowAnyHeader()
+                      ////.WithHeaders(corsOption.Headers.ToArray())
+                      ////.WithExposedHeaders(corsOption.ExposedHeaders.ToArray())
+                      ;
+                  });
+              });
+
+            return services;
+        }
     }
 }
diff --git a/CorsServer/CorsServer.WebApi31/appsettings.json b/CorsServer/CorsServer.WebApi31/appsettings.json
index 68b53b6..7013fb5 100644
--- a/CorsServer/CorsServer.WebApi31/appsettings.json
+++ b/CorsServer/CorsServer.WebApi31/appsettings.json
@@ -1,11 +1,10 @@
 {
   "urls": "http://*:5000",
   "CORS": {
-    "PolicyName": "",
-    "Origin": ["*"],
-    "Method": [ "*" ],
-    "Header": [ "*" ],
-    "ExposedHeaders": []
+    "Origins": ["*"],
+    "Methods": [ "*" ],
+    "Headers": [ "*" ],
+    "ExposedHeaders": ["x-custom-error"]
   },
   "Logging": {
     "LogLevel": {