[英]How do I use a comma seperated string from appsettings.json in my CORS service?
I am learning c#, and have created a .net 6.0 Core API server.我正在学习 c#,并创建了 .net 6.0 核心 API 服务器。
I wanted to add in CORS support, to have multiple front end servers connect to a single back end (if needed)我想添加 CORS 支持,让多个前端服务器连接到单个后端(如果需要)
I have the following in my appsettings.json (for development)我的 appsettings.json 中有以下内容(用于开发)
{
"frontEnd": "https://localhost:3000,https://localhost:3001,https:localhost:3002"
}
My Program.cs looks like the following我的 Program.cs 如下所示
{
public class Program
{
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
// Add dbcontext to the container.
builder.Services.AddDbContext<ModelContext>();
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var MyAllowedOrigins = "_myAllowedOrigins";
var frontEnd = builder.Configuration.GetValue<string>("frontEnd");
var cors = frontEnd.Split(',');
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowedOrigins,
policy =>
{
//policy.WithOrigins("https://localhost:3000",
// "https://localhost:3001",
// "https://localhost:3002");
//policy.WithOrigins(frontEnd);
Type type = policy.GetType();
if (type != null)
{
MethodInfo methodInfo = type.GetMethod("WithOrigins");
if (methodInfo != null)
{
try
{
methodInfo.Invoke(policy, cors);
} catch (Exception e)
{
Console.WriteLine(e);
}
}
}
});
});
builder.Logging.AddEventLog();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
app.Logger.LogInformation("Startup enviornment: Development");
} else if (app.Environment.IsProduction())
{
app.Logger.LogInformation("Startup enviornment: Production");
}
app.UseHttpsRedirection();
// Add to allow my react app to send to it without using development proxy?
// See: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-6.0
app.UseCors(MyAllowedOrigins);
app.UseAuthorization();
app.MapControllers();
app.Run();
}
}
}
the version works.该版本有效。
var MyAllowedOrigins = "_myAllowedOrigins";
var frontEnd = builder.Configuration.GetValue<string>("frontEnd");
var cors = frontEnd.Split(',');
builder.Services.AddCors(options =>
{
options.AddPolicy(name: MyAllowedOrigins,
policy =>
{
policy.WithOrigins("https://localhost:3000",
"https://localhost:3001",
"https://localhost:3002");
});
});
What is interesting is the policy.WithOrigins takes in a string array so 'cors' should function here.有趣的是 policy.WithOrigins 接受一个字符串数组,所以'cors'应该是 function 这里。
Using reflection fails, as it says the number of parameters entered does not match the method signature.使用反射失败,因为它表示输入的参数数量与方法签名不匹配。
Using the array built from my appsettings entry also fails but in a different way.使用从我的 appsettings 条目构建的数组也会失败,但方式不同。 The first host (localhost:3000) works, but a react app running on port 3002 fails with a message
第一个主机 (localhost:3000) 工作,但是在端口 3002 上运行的反应应用程序失败并显示一条消息
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://localhost:7197/*****.
跨域请求被阻止:同源策略不允许读取位于 https://localhost:7197/***** 的远程资源。 (Reason: CORS header 'Access-Control-Allow-Origin' missing).
(原因:缺少 CORS header 'Access-Control-Allow-Origin')。 Status code: 200.
状态码:200。
Using the string as entered (A comma separated list of hosts) causes none of the systems to function...使用输入的字符串(以逗号分隔的主机列表)不会导致任何系统 function...
Is there another way to set this up that would make it easier to have multiple front ends can be controlled by an appsettings.Production.json file?是否有另一种设置方法,可以更轻松地通过 appsettings.Production.json 文件控制多个前端?
Edit: The overarching issue was my mistyping https:localhost:3002 After that the cors array worked correctly.编辑:首要问题是我输入错误 https:localhost:3002 之后 cors 阵列正常工作。
Reflection is very much over-engineering this.反射在很大程度上过度设计了这一点。
You're successfully passing values one at a time here:您在这里一次成功地传递一个值:
policy.WithOrigins("https://localhost:3000",
"https://localhost:3001",
"https://localhost:3002");
And you can pass as many as you like.你可以随意通过。 That's because
WithOrigins
accepts a params string[]
parameter .那是因为
WithOrigins
接受params string[]
参数。 What params
basically means is that you can pass it multiple strings and the compiler will interpret them all as a string array. params
的基本意思是你可以传递多个字符串,编译器会将它们全部解释为字符串数组。
But you can also just pass a string array, which you have right here:但是你也可以只传递一个字符串数组,你在这里有:
var cors = frontEnd.Split(',');
So skip all the reflection and just pass your string values to the method:因此,跳过所有反射,只需将您的字符串值传递给该方法:
policy.WithOrigins(cors);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.