Monday, August 8, 2016

Developing an ASP.NET Web API_part1

ASP.NET Web API is a framework for building web APIs on top of the .NET Framework which makes use of HTTP. As almost any platform that you can think of has an HTTP library, HTTP services can be consumed by a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

ASP.NET Web API  leverages the concepts of HTTP and provides features such as:
  • Different Request/Response type supported like HTML, JSON and Binary Files (image/audio/video) and not just XML content as required by SOAP.
  • Built-in Action Mapping in controller, based on HTTP verbs (GET, POST, etc.)
Creating a Web API

To create a Web API, we will use Visual Studio. If you have Visual Studio 2012 or a higher version of it, then you are all good to start off with your Web API.

Starting a New Project
From the File menu, select New and then Project.

In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Set your preferred name for the project and click OK.


In the next window, you will be presented with a list of templates. While you can select any one of the templates from the list as they all will contain DLL files and configurations required to create Web API controllers, we will select the Empty Project Template to start with.


Adding a Controller
In Web API, a controller is an object that handles HTTP requests. Let's quickly add a controller for testing our Web API.

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller. We will call the controller TestController and select Empty API Controller from the Scaffolding options for Template.

Visual Studio will create our controller deriving from the ApiController class. Let's add a quick function here to test our API project by hosting it in IIS.
  1. public IEnumerable<string> Get()
  2.         {
  3.             return new string[] { "hello", "world" };
  4.         }
Hosting in IIS
Now we will add our service in IIS so that we can access it locally. Open IIS and right-click on Default Web Site to add our web service.

In the Add Application dialog box, name your service TestAPI and provide a path to the Visual Studio project's root path as shown below.


Click OK and our Web API Service is ready.

To test whether everything works fine, let's try the following URL in any browser: http://localhost/TestAPI/api/test.

If you have named your controller TestController as I have and also named your web service in IIS as TestAPI then your browser should return an XML file as shown below with string values hello world.


However, if your IIS doesn't have permission for the project folder, you might get an error message saying: "The requested page cannot be accessed because the related configuration data for the page is invalid." 

If you get this type of error then you can resolve it by giving read/write access to the IIS_IUSRS user group to the root folder.

Routing

Now let's look at how the URL that we provided to the browser is working.

ASP.NET Routing handles the process of receiving a request and mapping it to a controller action. Web API routing is similar to MVC routing but with some differences; Web API uses the HTTP request type instead of the action name in the URL (as in the case of MVC) to select the action to be executed in the controller.

The routing configuration for Web API is defined in the file WebApiConfig.cs. The default routing configuration of ASP.NET Web API is as shown in the following:
  1. public static class WebApiConfig
  2.     {
  3.         public static void Register(HttpConfiguration config)
  4.         {
  5.             config.Routes.MapHttpRoute(
  6.                 name: "DefaultApi",
  7.                 routeTemplate: "api/{controller}/{id}",
  8.                 defaults: new { id = RouteParameter.Optional }
  9.             );
  10.         }
  11.     }
The default routing template of Web API is api/{controller}/{id}. That is why we had "api" in our URL http://localhost/TestAPI/api/test.

When Web API receives a GET request for a particular controller, the list of matching actions are all methods whose name starts with GET. The same is the case with all the other HTTP verbs. The correct action method to be invoked is identified by matching the signature of the method.

This naming convention for action methods can be overridden by using the HttpGet,
HttpPut, HttpPost, or HttpDelete attributes with the action methods.

So, if we replace our previous code with this:
  1. [HttpGet]
  2.         public IEnumerable<string> Hello()
  3.         {
  4.             return new string[] { "hello", "world" };
  5.         }
And hit http://localhost/TestAPI/api/test on our browser, this will still return the same result. If we remove the HttpGet attribute, our Web API will not be able to find a matching Action for our request.

Now, let's add another method with same name Hello but with a different signature.
  1. [HttpGet]
  2.         public IEnumerable<string> Hello(string id)
  3.         {
  4.             return new string[] { id, "world" };
  5.         }
Using this method, we can now control what is being returned from our Service to some extent. If we test this method by calling http://localhost/TestAPI/api/test/namaste (notice an extra parameter at the end of the URL), we will get the following output:


So, now we have two methods called Hello. One doesn't take any parameters and returns strings "hello world", and another method takes one parameter and returns "yourparameter world".

While we have not provided the name of our method to be executed in our URL, the default ASP.NET routing understands the request as a GET request and based on the signature of the request (parameters provided), the particular method is executed. This is fine if we have only one GET or POST method in our controller, but since in any real business application there would usually be more than one such GET method, this default routing is not sufficient.

Let's add another GET method to see how the default routing handles it.
  1. [HttpGet]
  2.         public IEnumerable<string> GoodBye()
  3.         {
  4.             return new string[] { "good bye", "world" };
  5.         }
If we now build our project and call http://localhost/TestAPI/api/test/ in our browser, we will get an error that says "Multiple actions were found that match the request", which means the routing system is identifying two actions matching the GET request.


Customizing the Default Routing System of Web API
To be able to use multiple GET requests from the same controller, we need to change the HTTP request type identifier with an Action-based identifier so that multiple GET requests can be called.

This can be done by adding the following route configuration before the default configuration in WebApiConfig.cs.
  1. config.Routes.MapHttpRoute(
  2.                 name: "DefaultApi2",
  3.                 routeTemplate: "api/{controller}/{action}/{id}",
  4.                 defaults: new { id = RouteParameter.Optional }
  5.             );
Now test all three methods by calling these URLs:
  • http://localhost/TestAPI/api/test/hello
  • http://localhost/TestAPI/api/test/hello/my
  • http://localhost/TestAPI/api/test/goodbye
Written by Sovit Poudel
If you found this post interesting, follow and support us.
Suggest for you:

REST WCF Service in ASP.NET

Visual Basic.Net Tutorials for Beginners

Make VR Games in Unity with C# - Cardboard, Gear VR, Oculus

No comments:

Post a Comment