简体   繁体   中英

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. Given the following URLs:

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).

Following an example on this site , I've decorated my Controller action with a special route attribute:

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

And in my RouteConfig.cs file, I have my default route set up:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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