Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 822
NabilS Avatar asked Dec 07 '08 15:12

NabilS


People also ask

What is the difference between MVC and REST API?

MVC is about how the inner side of your app works. REST is about how your app "talks" with other apps. You can combine them. MVC is a design pattern for creating a separation of concerns and avoiding tightly coupled data, business, and presentation logic.

Is ASP.NET MVC RESTful?

ASP.NET MVC is one such framework that provides an inherently RESTful model for building XHTML-based services.

What is REST API in ASP.NET MVC?

NET Framework MVC. REST means “Representational State Transfer” and API means Application Programming Interface. Why do we use API? We use API to provide data to our application, it could be web apps, mobile apps, or any desktop app.

What is the difference between MVC routing and Web API routing?

If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.


2 Answers

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
    }
}
like image 77
Todd Smith Avatar answered Oct 29 '22 22:10

Todd Smith


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
    }
}
like image 24
Pablo Retyk Avatar answered Oct 29 '22 21:10

Pablo Retyk