【问题标题】:.NET MVC: Map Route Using Attribute On Action.NET MVC:使用动作属性映射路由
【发布时间】:2011-01-20 00:05:28
【问题描述】:

我对 MVC 很陌生,无法以某种方式找到这个问题的答案。 MVC 1(或 2,我想)中是否有内置架构允许您通过特定操作方法上的属性而不是 Global.asax 中的属性来指定路由映射?我可以看到它的使用在一定程度上受到了限制,因为多种方法可以与同一个动作相关联,因此需要不必要地复制路线,但我的问题仍然存在。

另外,除了我刚才提到的关于在多个方法上执行相同操作的问题之外,有没有人看到在实现这样的事情时有任何问题?

注意:我不是在问如何 来实现它。只检查这样的东西是否存在,如果不存在,是否比它的价值更麻烦。

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-2 url-routing


    【解决方案1】:

    您也可以尝试AttributeRouting,可通过NuGet 获得。披露——我是项目作者。我已经在个人和专业项目中使用它并取得了巨大的成功,除非我不得不这样做,否则我不会回到 ASP.NET MVC 的默认路由机制。看看github wiki。那里有许多功能的大量文档。

    简单用法如下所示:

    public class RestfulTestController : Controller
    {
        [GET("Resources")]
        public ActionResult Index()
        {
            return Content("");
        }
    
        [POST("Resources")]
        public ActionResult Create()
        {
            return Content("");
        }
    
        [PUT("Resources/{id}")]
        public ActionResult Update(int id)
        {
            return Content("");
        }
    
        [DELETE("Resources/{id}")]
        public ActionResult Destroy(int id)
        {
            return Content("");
        }
    }
    

    AttributeRouting 是高度可配置的,并且有一些扩展点。看看吧。

    【讨论】:

    • 帮助,在这里查看我的问题link
    【解决方案2】:

    我会为此推荐ASP.NET MVC Attribute Based Route Mapper。这是第三方库,不附带 ASP.NET MVC 1 或 2。用法如下:

    public SiteController : Controller
    {
        [Url("")]
        public ActionResult Home()
        {
            return View();
        }
    
        [Url("about")]
        public ActionResult AboutUs()
        {
            return View();
        }
    
        [Url("store/{category?}")]
        public ActionResult Products(string category)
        {
            return View();
        }
    }
    

    然后在您的global.asax 中,您只需调用routes.MapRoutes() 来注册您的操作路线。

    实现这一点非常简单。

    【讨论】:

    • 漂亮。我会看看。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多