SP1*_*SP1 2 asp.net-mvc asp.net-mvc-4 asp.net-mvc-5
我有一个要求,我必须映射以下网址
/amer/us/en/ = Home controller
/amer/us/en/login/index = Home controller
/amer/us/en/confirmation = Confirmation controller
Run Code Online (Sandbox Code Playgroud)
以及常规的默认操作。
例如,如果用户去
http:\\test.com --> http://test/home/index
http:\\test.com/amer/us/en/login/index --> http://test/home/index
http:\\test.com/amer/us/en/ --> http://test/home/index
Run Code Online (Sandbox Code Playgroud)
我正在研究属性路由,因此我在 HomeController 中添加了以下代码
[RoutePrefix("amer/us/en/")]
[Route("{action=index}")]
public class HomeController : Controller
{
}
Run Code Online (Sandbox Code Playgroud)
我收到此错误
The route prefix 'amer/us/en/' on the controller named 'Home' cannot begin or end with a forward slash,并且默认路由现在不起作用,因此http://test.com未加载任何内容。下面是我的默认 RouteConfig 类。
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapMvcAttributeRoutes();
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Run Code Online (Sandbox Code Playgroud)
对 MVC 非常陌生。有人可以告诉我我在这里做错了什么吗?
MVC 中的路由可以通过在类中定义路由RouteConfig或通过属性路由(或者可以使用区域)来工作。使用 RouteConfig 进行路由按照您定义路由的顺序进行。当请求到来时,MVC 会从上到下尝试你的路由,并执行第一个与请求的 url 匹配的路由。因此,您示例中的路由需求可以通过以下方式实现:
routes.MapRoute(
name: "RootLogin",
url: "amer/us/en/login/index/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "DefaultAmer",
url: "amer/us/en/{controller}/{action}{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Run Code Online (Sandbox Code Playgroud)
这会将登录映射为特殊路由,所有其他/amer/us/en/路由将转到controller之后的任何内容以及action其中的任何内容。最后一条路线,如果请求不是以以下开头/amer/us/en则将执行默认行为。
然而,看起来您想定义/amer/us/en/为一个区域,因此您可能也想看看它。
| 归档时间: |
|
| 查看次数: |
6004 次 |
| 最近记录: |