我决定使用属性路由而不是旧方法。 现在我遇到了一个问题:
这是我的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中没有提供其他参数时继续显示索引。 (就像它已经做的那样)
我该如何解决?
答案 0 :(得分:3)
您有此错误,因为此http://localhost:57922/articles
匹配许多路由,恰好有两个操作:
Index
中的ArticlesController
:articles
用作控制器,其匹配ArticlesController
名称,默认操作等于Index
。Index
中的HomeController
:articles
用作名为HomeController
的默认控制器的页面参数。要通过使用属性路由解决此问题,您必须在HomeController的Index操作中的page参数中添加约束,如下所示:
[Route("{page:int?}")]
public ActionResult Index(int? page)
{
//....
}
这样做这条路线将不匹配/文章因为articles
将被用作string
类型,并且不会匹配HomeController索引中的约束。