如何在没有URL动作的情况下获得路线
问题描述:
我希望自己的路线像这样:
I want my route to look like:
/product/123
我有一个GET操作,但我不希望它出现在URL中,它当前是:
I have an action GET but I don't want that in the URL, it is currently:
/product/get/123
如何获得?
Global.asax.cs
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属性来定义路径,如下所示:
You can use the Route attribute to define your path like this:
[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/
Which provides you the full route definition for "/product/{productId}" which is "/product/123" in your case. More details there: https://blogs.msdn.microsoft.com/webdev/2013/10/17/attribute-routing-in-asp-net-mvc-5/