hutongqing
2024-11-22 85458565e09bda1044d19b13d0b1ffb7ab576857
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WIDESEA_Core.Helper;
 
namespace WIDESEA_Core.Extensions
{
    /// <summary>
    /// Cors 跨域
    /// </summary>
    public static class CorsSetup
    {
        /// <summary>
        /// 跨域
        /// </summary>
        /// <param name="services"></param>
        /// <exception cref="ArgumentNullException"></exception>
        public static void AddCorsSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
 
            services.AddCors(c =>
            {
                if (!AppSettings.Get(new string[] { "Cors", "EnableAllIPs" }).ObjToBool())
                {
                    c.AddPolicy(AppSettings.Get(new string[] {"Cors", "PolicyName" }),
 
                        policy =>
                        {
                            policy
                            .WithOrigins(AppSettings.Get(new string[] { "Cors", "IPs" }).Split(','))
                            .AllowAnyHeader()//Ensures that the policy allows any header.
                            .AllowAnyMethod();
                        });
                }
                else
                {
                    //允许任意跨域请求
                    c.AddPolicy(AppSettings.Get(new string[] { "Cors", "PolicyName" }),
                        policy =>
                        {
                            policy
                            .SetIsOriginAllowed((host) => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials();
                        });
                }
 
            });
        }
    }
}