关于这个主题,我问了另一个问题:
这是当前的情况:在我的ASP.NET MVC 3 App上,我有一个如下定义的路由约束:
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)
我正在使用如下:
routes.MapRoute(
"Countries",
"countries/{country}",
new {
controller = "Countries",
action = "Index"
},
new {
country = new CountryRouteConstraint(
DependencyResolver.Current.GetService<ICountryRepository<Country>>()
)
}
); …Run Code Online (Sandbox Code Playgroud) asp.net-mvc unit-testing dependency-injection moq asp.net-mvc-3
我有一个博客应用程序,用户可以创建帖子,我使用实体框架从数据库创建模型。在帖子中我有一个条目UrlSlug。
但是,当我检查帖子的详细信息时:
控制器:
public ActionResult Details(int id = 0)
{
Post post = db.Posts.Find(id);
if (post == null)
{
return HttpNotFound();
}
return View(post);
}
Run Code Online (Sandbox Code Playgroud)
id它返回一个末尾带有以下内容的 url :http://localhost:52202/Post/Details/1
我尝试返回 post.UrlSlug (引发错误)以及更改我的 RouteConfig.cs 文件来使用urlslug(id它确实显示 urlslug,但由于控制器而无法找到页面)。如何更改此设置以便显示 urlslug 而不是 Post Table Id?
路由配置.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
看法:
@for (int i …Run Code Online (Sandbox Code Playgroud)