如何在没有URL动作的情况下获得路线 [英] How to get a route without the action in the URL

查看:129
本文介绍了如何在没有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/

这篇关于如何在没有URL动作的情况下获得路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆