using CrazyStudio.Core.Common.Tools.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CrazyStudio.Core.Common.Tools.Extensions
{
    public static class CorsExtension
    {
        /// <summary>
        /// 跨域配置
        /// </summary>
        /// <param name="services"></param>
        /// <param name="configuration"></param>
        public static void AddCors(this IServiceCollection services, IConfiguration configuration)
        {
            var corsUrls = configuration.GetSection("CorsUrls").Get<string[]>();

            if (corsUrls != null && corsUrls.Any())
            {
                //配置跨域
                services.AddCors(c =>
                {
                    c.AddPolicy("Policy", policy =>
                    {
                        //policy.SetIsOriginAllowed(origins => true)
                        policy.WithOrigins(corsUrls ?? Array.Empty<string>())
                        .AllowAnyHeader()//允许任意头
                        .AllowAnyMethod();//允许任意方法
                        //.AllowCredentials();//允许cookie
                    });
                });
            }
        }
    }
}
