Friday, March 4, 2011

ASP.NET MVC and REST URI's

How would I handle something like the below uri using ASP.NET MVC's routing capability:

http://localhost/users/{username}/bookmarks/ - GET
http://localhost/users/{username}/bookmark/{bookmarkid} - PUT

Which lists the bookmarks for the user in {username}.

Thanks

From stackoverflow
  • first you need to create a new route in global.aspx

    routes.MapRoute("Bookmarks", "{controller}/{user}/{action}/{id}");
    

    then add a new action

    public class UsersController : Controller
    {
        [AcceptVerbs("Post")]
        public void Bookmarks(string user, int? id)
        {
    
            //add your bookmark
        }
    }
    
  • You can use the [AcceptVerbs] attribute on your action method

    public class BookmarksController : Controller
    {
        [AcceptVerbs(HttpVerbs.Get)]
        public void Bookmarks(string user)
        {
    
            //add your bookmark
        }
    
        [AcceptVerbs(HttpVerbs.Post)]
        public void Bookmarks(string user, int? id)
        {
    
            //add your bookmark
        }
    }
    

0 comments:

Post a Comment