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.

71 lines
2.8 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中配置
//跨域请求
11 months ago
// 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" });
var exposedHeaders = AppSetting.app(new string[] { "Cors", "ExposedHeaders" });
11 months ago
12 months ago
services.AddCors(c =>
{
c.AddPolicy(policyName, policy =>
{
policy.WithOrigins(corsUrl
.Split(",", StringSplitOptions.RemoveEmptyEntries).ToArray())
//policy.WithOrigins("http://localhost:5001")//支持多个域名端口,注意端口号后不要带/斜杆比如localhost:8000/,是错的
.AllowAnyHeader().AllowAnyMethod().AllowCredentials();
if (!string.IsNullOrEmpty(exposedHeaders))
{
policy.WithExposedHeaders(exposedHeaders.Split(",", StringSplitOptions.RemoveEmptyEntries)); //允许cookie;
}
12 months ago
});
});
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中配置
//跨域请求
10 months ago
string policyName = AppSetting.app(new string[] { "Cors", "PolicyName" });
12 months ago
// 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;
}
}