开发者

.NET MVC: Map Route Using Attribute On Action

I'm pretty new to MVC and can't find an answer one way or another to this question. Is there a built in architecture in MVC 1 (or 2, I suppose) that allows you to specify a route mapping via an attribute on a specific action method, rather than in the Global.asax? I can see its use being limited to a degree as multiple methods can be tied to the same action thusly requiring routes to be unnecessarily duplicated, but my question still remains.

Also, does anyone see any gotcha's in implementing something like this, aside from the one I just mentioned about the same action on multiple methods?

Note: I'm not asking HOW to implement this. Only checking if 开发者_开发技巧something like this exists, and if not, if it's more trouble than it's worth.


You can also try AttributeRouting, which is available via NuGet. Disclosure -- I am the project author. I've used this in personal and professional projects with great success and would not go back to the default routing mechanism of ASP.NET MVC unless I had to. Take a look at the github wiki. There's extensive documentation of the many features there.

Simple usage looks like this:

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 is highly configurable and has a few extension points. Check it out.


I would recommend ASP.NET MVC Attribute Based Route Mapper for this. This is third party library and does not come with ASP.NET MVC 1 or 2. Usage is like the following:

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();
    }
}

Then in your global.asax, you just call routes.MapRoutes() to register your action routes.

It's dead simple to implement this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜