我想在我的CMS中为页面创建自定义slug,因此用户可以创建自己的SEO-urls(如Wordpress).
我以前通过"滥用"404路由在Ruby on Rails和PHP框架中执行此操作.无法找到请求的控制器时调用此路由,使我能够将用户路由到我的动态页面控制器以解析slug(如果没有找到页面,则从我将其重定向到真实404).这样,仅查询数据库以检查所请求的slug.
但是,在MVC中,仅当路由不适合默认路由时才会调用catch-all路由/{controller}/{action}/{id}.
为了仍然能够解析自定义slugs我修改了RouteConfig.cs文件:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
RegisterCustomRoutes(routes);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { Controller = "Pages", Action = "Index", id = UrlParameter.Optional }
);
}
public static void RegisterCustomRoutes(RouteCollection routes)
{
CMSContext db = new CMSContext();
List<Page> pages = db.Pages.ToList();
foreach (Page p in pages)
{
routes.MapRoute(
name: …Run Code Online (Sandbox Code Playgroud) 在我的ASP.NET MVC 3应用程序中,我有一个如下定义的路由约束:
public class CountryRouteConstraint : IRouteConstraint {
private readonly ICountryRepository<Country> _countryRepo;
public CountryRouteConstraint(ICountryRepository<Country> countryRepo) {
_countryRepo = countryRepo;
}
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
//do the database look-up here
//return the result according the value you got from DB
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
我在我的应用程序上使用Ninject作为IoC容器实现IDependencyResolver并且我注册了我的依赖项:
private static void RegisterServices(IKernel kernel) {
kernel.Bind<ICountryRepository<Country>>().
To<CountryRepository>();
}
Run Code Online (Sandbox Code Playgroud)
如何以依赖注入友好的方式使用此路由约束?
编辑
我找不到一种方法来传递这种依赖于单元测试:
[Fact]
public void country_route_should_pass() {
var mockContext = new Mock<HttpContextBase>();
mockContext.Setup(c => …Run Code Online (Sandbox Code Playgroud) asp.net-mvc unit-testing dependency-injection route-constraint asp.net-mvc-3