在运行时在dotnetcore中重新加载路由 [英] Reload routes on runtime in dotnetcore

查看:404
本文介绍了在运行时在dotnetcore中重新加载路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义路由,该路由从no-SQL数据库(MongoDB)中读取URL,并在应用程序启动时将它们添加到路由管道中,这是相当标准的"

I have a custom route that reads URLs from a no-SQL database (MongoDB) and add them to the route pipeline at moment that the application starts, which is "pretty standard"

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

something like this (in my startup.cs file):

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应用程序重新启动应用程序池(该应用程序是在Framework 4.5上开发的,显然在另一个池上运行)

the issue is that if I add another route to the database after the application has started I basically get a 404 since the routing system isn't aware of this new route, I think that what I need is add the missing routes at runtime or (less convenient) restart the application pool from another web application (which has been developed on framework 4.5 and obviously it runs on a different pool)

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

Any other thoughts on this? thanks.

推荐答案

第一个问题是database在您说:I add another route to the database时意味着什么,并且您还可以将路由保存在JSON,XML或INI文件中.

The first question is what does database mean when you say: I add another route to the database and wether you can keep your routes in a JSON, XML or INI file.

例如,如果您可以将路由保存在JSON文件中,则可以在运行时动态地使用路由(

If you can, for example, keep the routes in a JSON file, then there is possible for the routes to be dynamically available on runtime (as you can read in the ASP.NET Core Documentation)

您可以在此处找到有关此内容的完整博客文章.

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

Assuming that routes.json is a JSON file with structure similar to the following, and is in the same folder as Startup:

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

您可以通过以下方式配置Startup类:

You can configure the Startup class in the following way:

请注意,尽管我假设您可以将其转置为与MVC一起使用,但该示例并未使用MVC,而是使用了单独的路由包.

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参数,框架会将新配置重新注入到Configuration属性中.

At this point, while the application is running, you can modify the JSON file, save it, then because of the reloadOnChange: true parameter, the framework will reinject the new configuration into the Configuration property.

重新加载的实现是基于文件监视程序的,因此,如果您要为此使用数据库-SQL Server,那么我认为您必须自己实现.

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.

最诚挚的问候!

这篇关于在运行时在dotnetcore中重新加载路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆