我决定使用属性路由而不是旧的方式。
现在我面临一个问题:
这是我的RouteConfig:
这是我的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的index操作,关于页面也正常工作,分页也可以正常工作。
但是当我浏览到(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
我不明白为什么框架会混淆,因为我已经清楚地说明了我想要浏览以“articles”前缀开头的页面。
我希望应用程序在我浏览/article时显示索引视图,并且对于主页,当URL中没有提供其他参数时,我希望它继续显示索引(就像它已经做的那样)。
我该如何解决这个问题?