ASP.NET Web API
ASP.NET Web API is a framework which provides manageable resource oriented services for building HTTP RESTful (Representational State Transfer) services in a convenient way. Web API is an attractive solution for testing, managing, hosting, developing, and consuming HTTP (Hypertext Transfer Protocol) based services using the ASP.NET. ASP.NET Web API uses the full features of HTTP such as request/response headers, URIs, versioning, and content formats, as well as Web API supports MVC features including routing, Action Results, model binder, dependency injection and more.
Why does Web API stand alone?
Web API allows us to build HTTP Services. Today in this world most devices use the internet, which could be Web browsers, mobile devices (including Windows phone, apple, Androids), PCs, and laptops, and all of these require Web API Services. ASP.NET Web API can be used in conjunction with the ASP.NET Web Forms, ASP.NET MVC and WCF HttpBinding.
Features of Web API
- Web API is built on top of the ASP.NET platform.
- It is interoperable with other ASP.NET toolkits such as Web Forms and MVC.
- It uses support of ASP.NET Routing ad which enables us to build routes to our API.
- Strongly typed HTTP Request/Response.
- It uses NEW HTTPClient class that allows us to build HTTP Client side application.
HTTP Method and Operations
HTTP Method | Operation | Relative URI |
GET (Read) | Get a Member | /api/members/{username} |
POST (Create) | Create a new Member | /api/members |
PUT (Update) | Update a Member | /api/members/{username} |
DELETE (Delete) | Delete a Member | /api/members/{username} |
Let’s create a project for Web API. Open Visual Studio 2013, go to New and choose Project.
Expand Installed > Templates > Visual C# and choose an ASP.NET Web Application from the menu, give a name to your Web API project and finally click on the “OK” button.
So select a template. I’m going to create a Web API, so select a Web API template from the list of templates. Click on the ok button to create a Web API project including MVC features.
Your project is ready for use. You’re familiar with MVC, and lots of features in Web API are similar to MVC. I’m not saying that Web API and MVC features are exactly the same but as an ASP.NET MVC developer you can definitely differentiate between both of them.
How does MVC request Work?
To find this expand App_Start folder from the solution Explorer and select RouteConfig.cs file. You can find MVC default route under this file. When request comes to MVC it takes a URL and parses the first three segments of the URL so the first segment is controller, and then we have the action which finds the method inside this controller, and finally we have a default or optional ID parameter here.
How does Web API request Work?
Just like MVC Routeconfig file, we have WebApiConfig.cs file for the Web API. In the AppStart folder you can find that file. So just like in RouteConfig file, we have the default Web API route in the Web API. Web API routes prefix with api, and we can choose this name as anything like inverse API, Facebook API or whatever is our requirement. With the prefix api we also have controller and Id as well, the thing is that we don’t have actions here, the reason behind that is the Actions are HTTP methods and depending on the client request, for example if you have get request, then get() method would be called; if you have post request, then post() method would called.
routeTemplate: "api/{controller}/{id}",
Now go to your Web API controller and open the controller folder where you can find the Values Controller and click on it. In MVC if we want to call something then we have to use MVC controller, on the other hand, in Web API, if we want to call something we’re using API Controller.
So in API controller action methods are actually HTTP methods such as Get, Post, Put, Delete.
The figure shows that API Controller has four HTTP methods.
In the Values controller I'm going to make some changes inside the Get() method.
Run the application by pressing Ctrl+F5. I’ve put api as a prefix here and our controller name is Values controller.
So look into our output, we get xml representation of my string array.
Let’s try to create something more interesting, in this article I'm going with only Get() method. I need to create a model class. So just go to Models folder in the solution and right click on it and choose a New Item.
Go to Code panel and choose a class from the list; give an appropriate name for your class and click onto “Add” button.
In the model class I have two properties -- one is type of int; the second one is type of string.
Now go back to our controller which is value controller, in this we have two Get() methods so one method returns a list of Authors and the second method returns a single Author.
- public class ValuesController: ApiController {
-
- public IEnumerable < Author > Get() {
- return new List < Author > () {
- new Author() {
- AuthorId = 1, AuthorName = "Nitin Pandit"
- },
-
- new Author() {
- AuthorId = 2, AuthorName = "Amit Mishra"
- }
- };
- }
-
-
- public Author Get(int id) {
- if (id == 1)
-
- {
- return new Author() {
- AuthorId = 1, AuthorName = "Nitin Pandit"
- };
- } else if (id == 2) {
-
- return new Author() {
- AuthorId = 2, AuthorName = "Amit Mishra"
- };
- }
-
- return null;
- }
Here is the screenshot -
Now let’s run our Web API, press F5 to run it. So we successfully have XML representation of our list of Authors. In this request we get our Get() method.
Now try another Get() method, put id==1 in URL, so you’ll get Author, which has AuthorId=1 is return.
Let me try a second parameter that is two, I’ve got a second author with id of two.
If I pass something else in URL, such as id=12, then we get nothing because if we call null valu then that’s it.
We consume our Web API using Google chrome.
Now we’ll try the same request using Fiddler.
Fiddler
Fiddler is a Web debugging tool which captures all HTTP traffic between client machines to the Internet. Through Fiddler we can modify our HTTP request as per our convenience (such as in JSON, XML). You can download Fiddler from
here.
Let’s do some logs with fiddler that we perform in Google Chrome.
Here is the screenshot of fiddler, we try to make Get request and pass the Web API URL in URL tab under the composer after that simply click on to execute button in the top right side of the window.
After Executing URL, we’ll get a successful execution message at the left side of the window, double click on to it to trace the operation of our first request.
In the right side of the window, click on the raw tab where you can find JSON representation of our string data. You’ll remember when we make requests using Chrome we get XML representation of our string data, whereas in the case of Fiddler we’re getting it in JSON
We have another feature in Fiddler that is accepted, which specifies what kind of response a client can accept. It is an HTTP header. In Fiddler we can change the data in different formats. If we want to get our data in XML format, we need to write:
Accept:application/xml
If I want to see our data in JSON format I need to write something like this:
Accept:application/json
I want my data in xml format so we need to write accept value as Accept:application/xml and just click on the execute button.
You’ll get a successful message, double click on it and you’ll get your string data in XML format.
If you want your data in JSON format then you can have it that way. A process called Content Negotiation means that depending on the client request the server returns the format that way -- when you want XML it gives XML when you want JSON it gives you JSON as a result.
Let’s make a request to another method, let's pass an id first for one author, and after clicking onto the execute button you’ll get a success message on the left side of the window -- to see what happens, double click on it.
Click on the raw tab where you’ll find the JSON representation of your author which holds the first id.
Similarly, pass the second id to the URL, then click on the execute button.
You’ll find JSON representation of your second author which holds the second id.
You can also use Fiddler for testing purposes.
Thanks for reading this article, stay tuned with us for more on ASP.NET Web API.