在dotnetcore中重新加载运行时的路由
我有一个自定义路由,从无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
含义当你说: I add another route to the database
你可以将路由保存在JSON,XML或INI文件中。
例如,如果可以将路由保留在JSON文件中,那么路由可以在运行时动态提供( 正如您可以在ASP.NET核心文档中阅读 )
你可以在这里找到关于这个的完整博客文章 。
假设routes.json
是一个结构类似于以下内容的JSON文件,并且与Startup
在同一个文件夹中:
{ "route": "This is a route", "another-route": "This is another route", "default": "This is default!" }
您可以通过以下方式配置Startup
类:
请注意,此示例不使用MVC,而是使用单独的路由包,但我假设您可以将其转置为与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
属性。
重新加载的实现基于文件监视器,所以如果你想使用数据库 – 一个SQL Server,那么我认为你必须自己实现它。
A(完全没有完全提醒并在此提醒完整性)解决方案可以是创建一个控制台应用程序,在文件中添加数据库更改,然后在应用程序配置中使用该文件。
最好的祝福!
- 如何在ASP.NET Core 1中使用EF6
- 我应该在哪里开始ASP.NET Core中的持久后台任务?
- 在ASP.NET Core Web API中上载文件和JSON
- 找不到类型或命名空间名称“OpenIddictDbContext ”
- 刷新ASP.Net核心标识中的用户cookie票证
- 如何正确地在MVC6中注入HttpContext
- 用于Windows x64的ASP.NET核心应用程序(.NET Framework)仅在project.assets.json中出错
- Attribute.IsDefined在哪里进入DNX Core 5.0?
- asp.net 5中的Windows身份validation