简体   繁体   English

将多个URL路由到ASP.NET MVC中的同一视图

[英]Routing multiple URLs to the same view in ASP.NET MVC

I'm having some trouble trying to configure my ASP.NET MVC project to route multiple URLs to the same view. 我在尝试配置ASP.NET MVC项目以将多个URL路由到同一视图时遇到一些麻烦。 Given the following URLs: 给定以下URL:

localhost:1234
localhost:1234/Products
localhost:1234/Products/1
localhost:1234/Products/abcd
localhost:1234/Products/whatever

I would like each of these to route the user to the same view ( Products.cshtml , for instance). 我希望它们中的每一个都能将用户路由到同一视图(例如Products.cshtml )。

Following an example on this site , I've decorated my Controller action with a special route attribute: 按照此站点上的示例,我已经用特殊的route属性装饰了Controller动作:

[HttpGet]
[Route("Products/{id?}")]
public ActionResult Products(string id)
{
    return View();
}

And in my RouteConfig.cs file, I have my default route set up: RouteConfig.cs文件中,我设置了默认路由:

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

The localhost:1234 and the localhost:1234/Products links both work, but this isn't working for the remaining URLs. localhost:1234localhost:1234/Products链接都可以使用,但是不适用于其余的URL。

The attributes all look correct to me, so you probably just forgot to map the attribute routes. 这些属性对我来说看起来都是正确的,因此您可能只是忘了映射属性路由。 Remember to call MapMvcAttributeRoutes() somewhere in your initialization code. 请记住在初始化代码中的某个地方调用MapMvcAttributeRoutes()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM