在 ASP.NET MVC 4 中使用和不使用控制器名称进行路由 [英] Routing with and without controller name in ASP.NET MVC 4

查看:37
本文介绍了在 ASP.NET MVC 4 中使用和不使用控制器名称进行路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 ASP.NET MVC 4,但在设置路由时遇到了一些问题.你能告诉我如何设置我的路由以将 url 指向操作,如下所示:

I'm using ASP.NET MVC 4 and I have some problems settings up my routes. Could you tell my how to set up my routes to point urls to actions as follows:

  • "/" (或 "/Start") => PublicController.Start()
  • "/About" => PublicController.About()
  • "/MyPage" (或 "/MyPage/Summary") => MyPageController.Summary()
  • "/MyPage/Invoices" => MyPageController.Invoices()
  • "/MyPage/Invoice/72" => MyPageController.Invoice(int id)

是 url "/About" 把事情搞砸了,即没有指定控制器的 url.如果我让那一个工作,其他指定控制器的人就会停止工作.我想我可以为/About"创建一个单独的控制器,但如果我不需要(我有更多遵循该模式的网址),我宁愿不这样做.

It's the url "/About" that messes things up for me, i.e. a url that does not specify the controller. If I make that one work the others that do specify controller stop working. I could just create a separate controller for "/About" I guess, but I'd rather not if I don't have to (I have more urls following that pattern).

推荐答案

应该这样做:

routes.MapRoute(
    name: "About",
    url: "About",
    defaults: new { controller = "Public", action = "About" }
);

routes.MapRoute(
    name: "MyPageSummary",
    url: "MyPage",
    defaults: new { controller = "MyPage", action = "Summary" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Public", action = "Start", id = UrlParameter.Optional }
);

这篇关于在 ASP.NET MVC 4 中使用和不使用控制器名称进行路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆