Tuesday, January 14

Web API 2 and Attribute Routing

Introduction: Web API 2 supports a new type of routing, called attribute routing in addition to convention-based routing. Routing is how Web API matches a URI to an action. In attribute routing, we use attributes to define routes.
Here we'll create a REST API and we'll retrieve data using attribute routing.

Steps:

Create a new ASP.net Web application with Web API template.


Add Classes to Model: Add a class and name it as "Customer".


Replace the code with the following code:

Add another class named Order and replace the code with the following code.


Add Web API Controller: Right click the controller folder in solution explorer and then Add| Select Controller|. In the "Add Scaffold" dialog, select "Web API Controller with actions,using Entity Framework".


The Model and Controller folders in the solution explorer:

Seed the Database: From Tools Menu | Library Package Manager | Package Manager Console
In the package manager console window- enter the following command : Enable-Migrations

It creates "Migration Folder" and "configuration,cs" file. Open the configuration.cs file and add the following code to the configuration.seed method.


In the package manager console window, run the following commands:
Add-migration Initial
update-database

Add Route Attribute:

We'll use Controller to use Attribute Routing. We'll add RoutePrefix to the controller to define initial URI segment of all methods in controller. Then, add [Route] attribute to the actions.

The Route template for each method is the prefix plus the string specified in the "Route". The Route template for getOrder method includes a parameter of Integer type.

Output: Run the application and request for all orders (http://localhost#/api/orders). 
Response:

Now request for a order (http://localhost#/api/orders/2).
Response:
































No comments:

Post a Comment