- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
在 MVC-5 中,我可以在初始启动后通过访问 RouteTable.Routes
来编辑 routetable
。我希望在 MVC-6 中做同样的事情,这样我就可以在运行时添加/删除路由(对 CMS 很有用)。
在 MVC-5 中执行此操作的代码是:
using (RouteTable.Routes.GetWriteLock())
{
RouteTable.Routes.Clear();
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
但是我在 MVC-6 中找不到 RouteTable.Routes
或类似的东西。知道如何在运行时更改路由集合吗?
我想使用这个原理来添加,例如,在 CMS 中创建页面时添加一个额外的 url。
如果你有这样的类:
public class Page
{
public int Id { get; set; }
public string Url { get; set; }
public string Html { get; set; }
}
还有一个 Controller ,如:
public class CmsController : Controller
{
public ActionResult Index(int id)
{
var page = DbContext.Pages.Single(p => p.Id == id);
return View("Layout", model: page.Html);
}
}
然后,当一个页面被添加到数据库时,我重新创建了 routecollection
:
var routes = RouteTable.Routes;
using (routes.GetWriteLock())
{
routes.Clear();
foreach(var page in DbContext.Pages)
{
routes.MapRoute(
name: Guid.NewGuid().ToString(),
url: page.Url.TrimEnd('/'),
defaults: new { controller = "Cms", action = "Index", id = page.Id }
);
}
var defaultRoute = routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
通过这种方式,我可以将不属于约定或严格模板的页面添加到 CMS。我可以添加一个带有 url /contact
的页面,也可以添加一个带有 url /help/faq/how-does-this-work
的页面。
最佳答案
答案是没有合理的方法来做到这一点,即使找到了方法也不是好的做法。
基本上,过去 MVC 版本的路由配置就像一个 DI 配置——也就是说,你把所有东西都放在 composition root 中。然后在运行时使用该配置。问题是您可以在运行时将对象推送到配置中(许多人这样做),这不是正确的方法。
现在配置已经被真正的 DI 容器所取代,这种方法将不再有效。注册步骤现在只能在应用程序启动时完成。
自定义路由的正确方法远远超出 Route
类在过去的 MVC 版本中可以做的是 inherit RouteBase或路线。
AspNetCore(以前称为 MVC 6)具有类似的抽象,IRouter和 INamedRouter扮演同样的角色。很像它的前身,IRouter
只有两种方法可以实现。
namespace Microsoft.AspNet.Routing
{
public interface IRouter
{
// Derives a virtual path (URL) from a list of route values
VirtualPathData GetVirtualPath(VirtualPathContext context);
// Populates route data (including route values) based on the
// request
Task RouteAsync(RouteContext context);
}
}
此接口(interface)是您实现路由的双向特性的地方 - 用于路由值的 URL 和用于路由值的 URL。
CachedRoute<TPrimaryKey>
这是一个跟踪和缓存主键到 URL 的 1-1 映射的示例。它是通用的,我已经测试过无论主键是 int
它都有效。或 Guid
.
有一个可插拔 block 必须注入(inject),ICachedRouteDataProvider
可以实现对数据库的查询。您还需要提供 Controller 和操作,因此该路由足够通用,可以通过使用多个实例将多个数据库查询映射到多个操作方法。
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
public class CachedRoute<TPrimaryKey> : IRouter
{
private readonly string _controller;
private readonly string _action;
private readonly ICachedRouteDataProvider<TPrimaryKey> _dataProvider;
private readonly IMemoryCache _cache;
private readonly IRouter _target;
private readonly string _cacheKey;
private object _lock = new object();
public CachedRoute(
string controller,
string action,
ICachedRouteDataProvider<TPrimaryKey> dataProvider,
IMemoryCache cache,
IRouter target)
{
if (string.IsNullOrWhiteSpace(controller))
throw new ArgumentNullException("controller");
if (string.IsNullOrWhiteSpace(action))
throw new ArgumentNullException("action");
if (dataProvider == null)
throw new ArgumentNullException("dataProvider");
if (cache == null)
throw new ArgumentNullException("cache");
if (target == null)
throw new ArgumentNullException("target");
_controller = controller;
_action = action;
_dataProvider = dataProvider;
_cache = cache;
_target = target;
// Set Defaults
CacheTimeoutInSeconds = 900;
_cacheKey = "__" + this.GetType().Name + "_GetPageList_" + _controller + "_" + _action;
}
public int CacheTimeoutInSeconds { get; set; }
public async Task RouteAsync(RouteContext context)
{
var requestPath = context.HttpContext.Request.Path.Value;
if (!string.IsNullOrEmpty(requestPath) && requestPath[0] == '/')
{
// Trim the leading slash
requestPath = requestPath.Substring(1);
}
// Get the page id that matches.
TPrimaryKey id;
//If this returns false, that means the URI did not match
if (!GetPageList().TryGetValue(requestPath, out id))
{
return;
}
//Invoke MVC controller/action
var routeData = context.RouteData;
// TODO: You might want to use the page object (from the database) to
// get both the controller and action, and possibly even an area.
// Alternatively, you could create a route for each table and hard-code
// this information.
routeData.Values["controller"] = _controller;
routeData.Values["action"] = _action;
// This will be the primary key of the database row.
// It might be an integer or a GUID.
routeData.Values["id"] = id;
await _target.RouteAsync(context);
}
public VirtualPathData GetVirtualPath(VirtualPathContext context)
{
VirtualPathData result = null;
string virtualPath;
if (TryFindMatch(GetPageList(), context.Values, out virtualPath))
{
result = new VirtualPathData(this, virtualPath);
}
return result;
}
private bool TryFindMatch(IDictionary<string, TPrimaryKey> pages, IDictionary<string, object> values, out string virtualPath)
{
virtualPath = string.Empty;
TPrimaryKey id;
object idObj;
object controller;
object action;
if (!values.TryGetValue("id", out idObj))
{
return false;
}
id = SafeConvert<TPrimaryKey>(idObj);
values.TryGetValue("controller", out controller);
values.TryGetValue("action", out action);
// The logic here should be the inverse of the logic in
// RouteAsync(). So, we match the same controller, action, and id.
// If we had additional route values there, we would take them all
// into consideration during this step.
if (action.Equals(_action) && controller.Equals(_controller))
{
// The 'OrDefault' case returns the default value of the type you're
// iterating over. For value types, it will be a new instance of that type.
// Since KeyValuePair<TKey, TValue> is a value type (i.e. a struct),
// the 'OrDefault' case will not result in a null-reference exception.
// Since TKey here is string, the .Key of that new instance will be null.
virtualPath = pages.FirstOrDefault(x => x.Value.Equals(id)).Key;
if (!string.IsNullOrEmpty(virtualPath))
{
return true;
}
}
return false;
}
private IDictionary<string, TPrimaryKey> GetPageList()
{
IDictionary<string, TPrimaryKey> pages;
if (!_cache.TryGetValue(_cacheKey, out pages))
{
// Only allow one thread to poplate the data
lock (_lock)
{
if (!_cache.TryGetValue(_cacheKey, out pages))
{
pages = _dataProvider.GetPageToIdMap();
_cache.Set(_cacheKey, pages,
new MemoryCacheEntryOptions()
{
Priority = CacheItemPriority.NeverRemove,
AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(this.CacheTimeoutInSeconds)
});
}
}
}
return pages;
}
private static T SafeConvert<T>(object obj)
{
if (typeof(T).Equals(typeof(Guid)))
{
if (obj.GetType() == typeof(string))
{
return (T)(object)new Guid(obj.ToString());
}
return (T)(object)Guid.Empty;
}
return (T)Convert.ChangeType(obj, typeof(T));
}
}
这是数据提供程序的实现,基本上是您需要在 CMS 中执行的操作。
public interface ICachedRouteDataProvider<TPrimaryKey>
{
IDictionary<string, TPrimaryKey> GetPageToIdMap();
}
public class CmsCachedRouteDataProvider : ICachedRouteDataProvider<int>
{
public IDictionary<string, int> GetPageToIdMap()
{
// Lookup the pages in DB
return (from page in DbContext.Pages
select new KeyValuePair<string, int>(
page.Url.TrimStart('/').TrimEnd('/'),
page.Id)
).ToDictionary(pair => pair.Key, pair => pair.Value);
}
}
这里我们在默认路由之前添加路由,并配置其选项。
// Add MVC to the request pipeline.
app.UseMvc(routes =>
{
routes.Routes.Add(
new CachedRoute<int>(
controller: "Cms",
action: "Index",
dataProvider: new CmsCachedRouteDataProvider(),
cache: routes.ServiceProvider.GetService<IMemoryCache>(),
target: routes.DefaultHandler)
{
CacheTimeoutInSeconds = 900
});
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
// Uncomment the following line to add a route for porting Web API 2 controllers.
// routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
});
这就是它的要点。您仍然可以稍微改进一下。
我个人会使用工厂模式并将存储库注入(inject) CmsCachedRouteDataProvider
的构造函数中而不是硬编码DbContext
例如,无处不在。
关于c# - 启动后更改MVC6的路由集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32565768/
我有一个我想暂时存储的对象。该对象现在在 Controller 中, Controller 将生成一个 View 。 AJAX 请求从 View 发送到下一个 Controller 。那一刻我需要先前
从MVC 2开始,我们可以轻松创建区域。现在,我的问题与嵌套区域(区域内部的区域)有关。 选择我的“father”区域文件夹,右键单击> Add> NO选项以获取new Area。 是否有可能以其他方
关闭。这个问题不满足Stack Overflow guidelines .它目前不接受答案。 想改善这个问题吗?更新问题,使其成为 on-topic对于堆栈溢出。 7年前关闭。 Improve thi
我已经尝试了一些谷歌搜索和堆栈流搜索,但事实证明这比我想象的要难找到。我需要为我们的商店迁移到 ASP.NET MVC 2 的管理提供理由。最大的帮助将是任何企业级站点或使用 ASP.NET MVC
关闭。这个问题是opinion-based 。目前不接受答案。 想要改进这个问题吗?更新问题,以便 editing this post 可以用事实和引文来回答它。 . 已关闭 6 年前。 Improv
我有一些常见的网页,它们将出现在多个 MVC 应用程序中。对于这些页面,我想在不同的 MVC 网站之间重用相同的源代码( Controller + View )。这样做的最佳方法是什么? ASP.NE
我正在使用 Spring MVC 来构建我的应用程序。 当用户在浏览器中运行应用程序时,我想显示一个默认的 jsp。我不想用 web.xml 中的标记。 我想我可以用 我已经创建了一个文件夹并添
我可能在这里分析过度了,但是根据我对 MVC 的阅读,似乎有很多关于如何做事情的观点。 是否有一个“最佳实践”网站或文档来定义 MVC 各个部分的职责? 请记住,我使用 EF/Repository&U
当杰里米和查德 posted about their FubuMvc project ,他们提到的差异化因素之一是他们的“雷霆穹顶校长”: The “Thunderdome Principle” –
我正在为 Spring MVC 应用程序实现缓存清除系统。 为了让这个系统正常工作,我必须从给定的 url 中删除“缓存破坏代码”。假设我生成的缓存破坏代码是“123”,我有一个 .css url:/
在调试 ASP.NET MVC 源时,我发现使用了“MVC-ControllerTypeCache.xml” 文件。但我无法理解这个文件的用途。我的意思是这个文件存储在哪里?asp.net MVc 如
我刚刚在我的本地机器上安装了 Visual Studio 11 和 MVC 4 beta。但是,每当我打开一个 MVC 3 项目(我想保留为 MVC 3)时,所有引用都已更新为版本 4 DLL。当然它
我有一个 MVC 3 应用程序,它具有一些核心功能(最重要的是自动化),但主要用作不同区域或模块的门户。我想将它组织到不同的模块中,只需稍作更改也可以部署为他们自己的网站。 该项目由论坛、博客引擎、用
我有自己的服务器,正在考虑将我的一个解决方案升级到 ASP.NET MVC 4,然后再升级其余的 (3+)。 作为其中的一部分,我下载了 the standalone installer对于 ASP.
构图 我有一个 MVC 项目,其中包含 C# 类,这些类最终通过 ajax 等进行序列化和使用。我使用 TypeLite 生成这些 C# 类的定义( here 讨论了 TypeLite 的替代方案),
我正在尝试了解现代 Web 应用程序架构。在 ASP.NET MVC 中,所有业务逻辑类都在 Model 中,Controller 接受并引导用户请求。如果我使用它,是否可以使用本身是 MVC 架构但
我有一个带有 OWIN 的 WebAPI 2 应用程序。现在我正在尝试向所有内容添加一个 MVC 5 Controller ,但没有找到我的 MVC 路由。我收到以下错误: No HTTP resou
在 MVC 3 中,他们添加了我一直在使用的依赖解析器。在回答某人对您发表评论的问题时,您应该使用 Ninject MVC 3 插件。 所以我的问题是为什么要使用它而不是内置的?如果这是要走的路,你如
我是 ASP.NET MVC 的新手,我正在寻找最不痛苦的方法来设置全局错误处理、日志记录和报告(通过电子邮件)。仅供引用,我的 ASP.NET MVC 应用程序在 Azure 中作为 Web 角色托
何时使用 MVC View 页面和 MVC View 内容页面?它们有什么区别? 最佳答案 **MVC View Page 用于创建页面,MVC VewP Content Page 用于创建页面并指定
我是一名优秀的程序员,十分优秀!