|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
|
|
namespace DS.Module.Core.ServiceExtensions;
|
|
|
|
|
|
/// <summary>
|
|
|
/// 跨域服务
|
|
|
/// </summary>
|
|
|
public static class CorsInstall
|
|
|
{
|
|
|
/// <summary>
|
|
|
/// 将模块服务添加到依赖注入服务容器中
|
|
|
/// </summary>
|
|
|
/// <param name="services">依赖注入服务容器</param>
|
|
|
/// <returns></returns>
|
|
|
public static IServiceCollection AddCorsInstall(this IServiceCollection services)
|
|
|
{
|
|
|
if (services == null) throw new ArgumentNullException(nameof(services));
|
|
|
|
|
|
//跨域第二种方法,声明策略,记得下边app中配置
|
|
|
//跨域请求
|
|
|
// string policyName = AppSetting.Configuration["Cors:PolicyName"];
|
|
|
// var corsUrl = AppSetting.Configuration["Cors:Url"];
|
|
|
string policyName = AppSetting.app(new string[] { "Cors", "PolicyName" });
|
|
|
var corsUrl = AppSetting.app(new string[] { "Cors", "Url" });
|
|
|
|
|
|
services.AddCors(c =>
|
|
|
{
|
|
|
c.AddPolicy(policyName, policy =>
|
|
|
{
|
|
|
policy.WithOrigins(corsUrl
|
|
|
.Split(",", StringSplitOptions.RemoveEmptyEntries).ToArray())
|
|
|
//policy.WithOrigins("http://localhost:5001")//支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
|
|
|
.AllowAnyHeader().AllowAnyMethod().AllowCredentials(); //允许cookie;
|
|
|
});
|
|
|
});
|
|
|
|
|
|
return services;
|
|
|
}
|
|
|
|
|
|
/// <summary>
|
|
|
/// 将模块服务添加到依赖注入服务容器中
|
|
|
/// </summary>
|
|
|
/// <param name="services">依赖注入服务容器</param>
|
|
|
/// <returns></returns>
|
|
|
public static IServiceCollection AddAnyCorsInstall(this IServiceCollection services)
|
|
|
{
|
|
|
if (services == null) throw new ArgumentNullException(nameof(services));
|
|
|
|
|
|
//跨域第二种方法,声明策略,记得下边app中配置
|
|
|
//跨域请求
|
|
|
string policyName = AppSetting.app(new string[] { "Cors", "PolicyName" });
|
|
|
// var corsUrl = AppSetting.Configuration["Cors:Url"];
|
|
|
services.AddCors(c =>
|
|
|
{
|
|
|
c.AddPolicy(policyName, policy =>
|
|
|
{
|
|
|
policy.AllowAnyOrigin()
|
|
|
//policy.WithOrigins("http://localhost:5001")//支持多个域名端口,注意端口号后不要带/斜杆:比如localhost:8000/,是错的
|
|
|
.AllowAnyHeader().AllowAnyMethod(); //允许cookie;
|
|
|
});
|
|
|
});
|
|
|
|
|
|
return services;
|
|
|
}
|
|
|
} |