如何在URL中没有操作的情况下获取路由
我希望我的路线看起来像:
/product/123
我有一个动作GET,但我不想在URL中,它目前是:
/product/get/123
怎么弄这个?
的Global.asax.cs
RouteConfig.RegisterRoutes(RouteTable.Routes); public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = UrlParameter.Optional }, new[] { "MyApp.Web.Controllers" } ); }
您可以使用Route属性来定义您的路径,如下所示:
[Route("product")] public class ProductController { [Route("{productId}"] public ActionResult Get(int productId) { // your code here } }
其中为您提供了“/ product / {productId}”的完整路径定义,在您的案例中为“/ product / 123”。 更多细节: https : //blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/
在默认路由之前的routes.MapRoute中添加此代码。
routes.MapRoute( name: "Product", url: "Product/{id}", defaults: new { controller = "product", action = "get"}