【发布时间】:2015-11-04 22:41:36
【问题描述】:
我决定使用属性路由而不是旧方式。 现在我面临一个问题:
这是我的 RouteConfig:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.LowercaseUrls = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
}
}
这是我的 HomeController:
public class HomeController : Controller
{
// some database stuff
[Route("{page?}")]
public ActionResult Index(int? page)
{
int pageNumber = page ?? 1;
int pageCount = 1;
return View(db.SelectPaged(pageNumber, pageCount));
}
[Route("about")]
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
}
这是 ArticleController:
[RoutePrefix("articles")]
public class ArticlesController : Controller
{
private ClearDBEntities db = new ClearDBEntities();
// GET: Articles
[Route("")]
public ActionResult Index()
{
var articles = db.Articles.Include(a => a.Admin);
return View(articles.ToList());
}
// GET: Articles/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Article article = db.Articles.Find(id);
if (article == null)
{
return HttpNotFound();
}
return View(article);
}
问题:
当我运行应用程序并浏览默认地址 (http://localhost:57922) 时,一切正常。它显示了来自 homecontroller 的索引操作,关于页面也可以正常工作,分页也是如此。
但是当我浏览到 (http://localhost:57922/article) 时,它给了我:
Server Error in '/' Application.
Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
The request has found the following matching controller types:
ClearBlog.Controllers.ArticlesController
ClearBlog.Controllers.HomeController
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Multiple controller types were found that match the URL. This can happen if attribute routes on multiple controllers match the requested URL.
The request has found the following matching controller types:
ClearBlog.Controllers.ArticlesController
ClearBlog.Controllers.HomeController
我不明白当我明确表示要浏览带有“文章”前缀的页面时,框架会如何混淆。
我希望应用程序在浏览到 /article 时显示索引视图。至于主页,我希望它在 url 中没有提供其他参数时继续显示索引。 (就像它已经做的一样)
我该如何解决?
【问题讨论】:
标签: asp.net-mvc routing