gpt4 book ai didi

c# - 在 dotnetcore 中运行时重新加载路由

转载 作者:行者123 更新时间:2023-11-30 21:46:10 26 4
gpt4 key购买 nike

我有一个自定义路由,它从非 SQL 数据库 (MongoDB) 读取 URL,并在应用程序启动时将它们添加到路由管道,这是“非常标准的”

像这样的东西(在我的 startup.cs 文件中):

app.UseMvc(routes =>
{
routes.MapRoute(
"default",
"{controller=Home}/{action=Index}/{id?}");
routes.Routes.Add(
new LandingPageRouter(routes, webrequest, memoryCache, Configuration));
// this custom routes adds URLs from database
}

问题是,如果我在应用程序启动后向数据库添加另一条路由,我基本上会收到 404,因为路由系统不知道这条新路由,我认为我需要的是添加丢失的路由运行时或(不太方便)从另一个 Web 应用程序(已在框架 4.5 上开发,显然它运行在不同的池上)重新启动应用程序池

对此还有其他想法吗?谢谢。

最佳答案

第一个问题是 database 是什么意思,当你说:我向数据库添加另一个路由 并且你是否可以将你的路由保存在 JSON、XML 或 INI 中文件。

例如,如果您可以将路由保存在 JSON 文件中,那么路由就可以在运行时动态可用 (as you can read in the ASP.NET Core Documentation)

You can find a full blog post about this here .

假设 routes.json 是一个 JSON 文件,其结构类似于以下内容,并且与 Startup 位于同一文件夹中:

{
"route": "This is a route",
"another-route": "This is another route",
"default": "This is default!"
}

您可以按以下方式配置Startup类:

Note that this example does not use MVC but the separate routing package, although I assume you can transpose it to work with MVC.

public class Startup
{
public IConfiguration Configuration {get;set;}
public Startup(IHostingEnvironment env)
{
var configurationBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("routes.json", optional: false, reloadOnChange: true);

Configuration = configurationBuilder.Build();
}
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
}
public void Configure(IApplicationBuilder app)
{
var routeBuilder = new RouteBuilder(app);

routeBuilder.MapGet("{route}", context =>
{
var routeMessage = Configuration.AsEnumerable()
.FirstOrDefault(r => r.Key == context.GetRouteValue("route")
.ToString())
.Value;

var defaultMessage = Configuration.AsEnumerable()
.FirstOrDefault(r => r.Key == "default")
.Value;

var response = (routeMessage != null) ? routeMessage : defaultMessage;

return context.Response.WriteAsync(response);
});

app.UseRouter(routeBuilder.Build());
}
}

此时,在应用运行时,可以修改JSON文件,保存,然后由于reloadOnChange: true参数,框架会重新注入(inject)新的配置到配置属性。

The implementation of the reload is based on a file watcher, so if you want to use a database for this - a SQL Server, then I think you have to implement this yourself.

A (not pretty at all and reminded here just for completeness) solution could be to create a console application that adds database changes in a file, then use that file in the application configuration.

最好的问候!

关于c# - 在 dotnetcore 中运行时重新加载路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39460585/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com