You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
2.3 KiB
C#

12 months ago
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"];
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.Configuration["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;
}
}