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.

65 lines
2.5 KiB
C#

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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;
}
}