Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 22, 2016 12:00 pm

Developing an ASP.NET Web API

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.

Starting a new project in Visual Studio

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.

Choosing WEB API project template

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.

Adding first API Controller

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.

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.

Hosting in IIS

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.

Adding new application in IIS

Click OK and our Web API Service is ready.

To test whether everything works fine, let's try the following URL in any browser: https://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.

Response from Test Controller

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:

The default routing template of Web API is api/{controller}/{id}. That is why we had "api" in our URL https://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:

And hit https://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.

Using this method, we can now control what is being returned from our Service to some extent. If we test this method by calling https://localhost/TestAPI/api/test/namaste (notice an extra parameter at the end of the URL), we will get the following output:

Response from Test Controller 2

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.

If we now build our project and call https://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.

Error Response from Test Controller

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.

Now test all three methods by calling these URLs:

Web API Service Structure for Mobile Devices

Now that the basic idea of how Actions from Controllers can be exposed through the API is understood, let's look at how an API Service can be designed for clients.

Image 9 Web API Service Structure Flow

The ASP.NET Web API request pipeline receives requests from the client application, and an action method in a controller will be invoked. The action method will, in turn, invoke the Business layer for fetching or updating data, which, in turn, invokes the Repository class to return data from the database.

Based on this design pattern, let's create a sample API that exposes a list of Classified items as a service to its clients.

Create a class called ClassifiedModel inside the Models folder.

Create two folders BLL and DAL representing the Business Logic Layer and Data Access Layer.

Create a class called ClassifiedRepository inside the DAL folder where we will hard-code some data for the classified list and expose the list through a static method.

Let's add another class ClassifiedService inside the BLL folder now. This class will contain a static method to access the repository and return business objects to the controller. Based on the search parameters, the method will return the list of classified items.

Finally, now we will create our Web API controller for the classified listing related methods.

Similar to how we created our first TestController, let's create an API controller with empty read/write actions called ClassifiedsController and add the following two Action methods.

Now, we have two Actions exposed through the API. The first GET method will be invoked if there is a keyword to be searched that is passed along with the request. If there is no input parameter, then the second GET method will be invoked. Both methods will return a list of our Classified model objects.

Do not forget to add all the required references to the namespaces in each of the added class files. Build the project, and we are ready to test both of these methods now.

To display results containing the search parameter "house", hit the following URL in the browser: https://localhost/TestAPI/api/classifieds/get/house.

We should get the following response in the browser:

GET Request with house as parameter

To see the entire list of classifieds, hit the URL without passing any parameters: https://localhost/TestAPI/api/classifieds/get/.

You should see the following result:

GET Request without any parameter

We can add any number of Actions and Controllers in the same manner as desired by the clients.

Content Negotiation

Up to now, we've seen examples of API that send XML responses to the clients. Now let's look at other content types like JSON and Image response, which fall under the topic of Content Negotiation.

The HTTP specification (RFC 2616) defines content negotiation as “the process of selecting the best representation for a given response when there are multiple representations available." Thanks to Web API's Content Negotiation feature, clients can tell Web API services what content format it accepts, and Web API can serve the client with the same format automatically, provided that the format is configured in Web API.

Requesting JSON Format

The HTTP Accept header is used to specify the media types that are acceptable to the
client for the responses. For XML, the value is set as "application/xml" and for JSON "application/json".

In order to test our API with the HTTP Accept headers, we can use the extensions available for the browsers that allow us to create custom HTTP requests.

Here, I am using an extension called HTTP Tool available for Mozilla Firefox to create the Accept header that specifies JSON as the response type.

Creating HTTP Request Headers

As you can see from the image, the response that is being received is in JSON format.

Image File as Response

Finally, let's see how we can send an Image file as a response through Web API.

Let's create a folder called Images and add an image called "default.jpg" inside it, and then add the following Action method inside our ClassifiedsController.

Also, these two namespaces should be included: System.Web, System.Web.Http.

Here we are creating an HTTP response using the HttpResponseMessage class and setting the image bytes as the response content. Also, we are setting the Content-Type header to "image/png".

Now, if we call this action in our browser, Web API will send our default.jpg image as a response: https://localhost/TestAPI/api/classifieds/Getimage/.

Sending Image as response from Web API

Conclusion

In this tutorial, we looked at how ASP.NET Web API can easily be created and exposed to clients as Action methods of MVC Controllers. We looked at the default and custom routing system, created the basic structure of a real-time business application API Service, and also looked at different response types.

And if you're looking for some additional utilities to purchase, review, or use, check out the .NET offering in CodeCanyon.

I hope you enjoyed this tutorial and found it useful for building your Web APIs for mobile devices. Thanks!


Original Link:

Share this article:    Share on Facebook
No Article Link

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code