C# 基于域的.net核心交换应用程序设置配置
如何在Startup.csC# 基于域的.net核心交换应用程序设置配置,c#,asp.net-core,asp.net-core-configuration,C#,Asp.net Core,Asp.net Core Configuration,如何在Startup.csConfigureServices中获取当前域?基本上,我需要根据域更改一些设置。所有设置都存储在appsettings.json中 appsettings.json { "Logging": { "LogLevel": { "Default": "Information", "Microsoft": "Warning", "Microsoft.Hosting.Lifetime": "Information" }
ConfigureServices
中获取当前域?基本上,我需要根据域更改一些设置。所有设置都存储在appsettings.json中
appsettings.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Brands": [
{
"Name": "Brand A",
"Domain": "branda.com",
"Uri": [ "promo1", "promo2" ],
"AssetsDir": "assets/branda"
},
{
"Name": "Brand B",
"Domain": "brandb.com",
"Uri": [ "promo1", "promo2" ],
"AssetsDir": "assets/brandb"
}
]
}
startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
var brands = Configuration.GetSection("Brands")
.GetChildren()
.ToList();
// look up brands based on the current domain
// load settings into config
services.AddRazorPages();
}
正如您在评论中提到的,我建议您加载所有设置,并使用操作筛选器来标识当前域并加载所需的设置 下面是一些识别域的伪代码
public class TenantAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
var fullAddress = actionExecutingContext.HttpContext?.Request?
.Headers?["Host"].ToString()?.Split('.');
if (fullAddress.Length < 2)
{
actionExecutingContext.Result = new StatusCodeResult(404);
base.OnActionExecuting(actionExecutingContext);
}
else
{
var subdomain = fullAddress[0];
//We got the subdomain value, next verify it from database and
//inject the information to RouteContext
}
}
}
公共类租户属性:ActionFilterAttribute
{
公共重写无效OnActionExecuting(ActionExecutingContext ActionExecutingContext)
{
var fullAddress=actionExecutingContext.HttpContext?请求?
.Headers?[“主机”].ToString()?.Split('.');
if(fullAddress.Length<2)
{
actionExecutingContext.Result=新状态码结果(404);
base.OnActionExecuting(actionExecutingContext);
}
其他的
{
var subdomain=fullAddress[0];
//我们得到了子域值,接下来从数据库和
//将信息注入RouteContext
}
}
}
此链接也可能对您有所帮助-我认为您无法做到这一点。域是每个请求的值,当应用程序加载时,启动将运行一次。如果您的应用程序在每个部署中只处理一个域,那么您应该使您的配置对部署是唯一的。@JasonWadsworth感谢您的快速响应。好的,我可能会获得所有配置设置,并且仍然将其存储为配置选项。然后在我的控制器中,我将进行切换。这有意义吗?有什么建议吗?谢谢你的建议。我也会试试这个