Showing posts with label HTTP Services. Show all posts
Showing posts with label HTTP Services. Show all posts

Sunday, January 12, 2014

Self Hosting ASP.NET Web API Service

Windows Communication Foundation (WCF) services provide great flexibility of hosting. We have a number of options to host them. They are Managed Windows Service, Managed Application, Internet Information Services (IIS) and Windows Process Activation Service (WAS). Choosing WAS doesn't seem like an option as this is specially useful for non-HTTP based services, while ASP.NET Web API services are HTTP services.

I thought this would be a good idea to explore the number of different options to host ASP.NET Web API Service and when it would make more sense to choose one of them. In this post, we are going to look at Self Hosting of ASP.Net Web API service using Microsoft.Aspnet.WebApi.SelfHost nuget package. Please remember that this is not a recommended option (any more). For all new services, it is recommended to use Katana, which is an OWIN implementation.

Self Hosting is a generic term used to refer any application which provides its own code (non-declarative) for initializing the hosting environment and maintaining its lifetime[Bustamante, Michele Leroux - CODE Magazine - Jan / Feb 2007]. They can be either of Console, WPF or Windows Forms or a managed Windows Service.



In order to self host ASP.Net Web API Service, we need to install Microsoft.Aspnet.WebApi.SelfHost nuget package. This would install all the required assemblies needed to self host this type of services.



All the required nuget dependencies are also installed with this installation. We can have a look at the installed nuget packages using Package Visualizer. The tool draws a package dependencies graph for all projects in the solution.



Please note the weird dependency for Microsoft.AspNet.WebApi.Core 5.0.0 on Microsoft.AspNet.WebApi.Client 5.0.0. Mark Seemann has also tweeted about this recently. In case you are curious, D in SOLID is not Dependency Injection as I have found many to state that. This is Dependency Inversion Principle. Lostechies.com has a wonderful explanation of the suite of principles for software design.

Now we just need to provide necessary configuration for hosting the service. Since we have already installed the nuget package, we have all the necessary types required for hosting the service. It also supports attribute routing for self hosting. Let's update the Main method in Program.cs as follows:


Now you might be wondering why in the world I have assigned the full name of InstituteController type to a local variable and haven't even used the variable. Actually I never intended to use the variable. We just need to load the assembly containing the controller type. If the assembly is not loaded, the controller type will not be loaded in the app domain resulting in the failure of resource request. You can find other solutions as well e.g. here someone has recommended a custom assembly resolver. Avoiding the load of assembly would result in a "Resource Not Found" response from the service.



You might have noticed HttpSelfHostConfiguration instead of HttpConfiguration to configure the service. Actually, the type inherits from that. The type is available in System.Web.Http.SelfHost namespace. The assembly is downloaded and referenced as part of the nuget package installation described above. HttpSelfHostServer is also available in the same namespace and assembly.



Now we just need to run and request a resource from a client. Let's run the console application. We can send a request using a browser. Here we are using one of the actions in InstituteController, which results in the following response:



Download

Saturday, December 14, 2013

ASP.NET Web API 2 - Action's Response and IHttpActionResult

This is a continuation of our discussion about ASP.NET Web API. In this post we are trying to understand how results generated by actions are interpreted and further processed by ASP.NET Web API message pipeline. In the previous posts, we have defined various actions with three different types of returned data. There are following return types you might see for Web API action implementations:
  1. HttpResponseMessage
  2. IHttpActionResult [ASP.NET Web API 2]
  3. Any other type
  4. void
Every ASP.NET Web Api requests passes through a pipeline before a particular controller's action is invoked. The action's response can also be processed and passed through various stages before it is pushed to the requester. This is also possible that all the formatting is done at the action's side generating an HttpResponseMessage, resulting in bypassing all these stages. At the end, irrespective of returned data, an HttpResponseMessage is generated.



ASP.NET Web API message life cycle poster can be obtained from Microsoft's download center. If you understand the flow of message as described in this poster then you understand it all. So make sure that all the particular pieces are looked at with great emphasis and care.



Return type as void
These are the simplest of all actions from development perspective. They are specially useful for the requests with HTTP verbs including PUT / DELETE and POST. In these cases, the client is not interested in the data returned form the service. They are for pushing data to the service. Let's just make sure that having a return type as void doesn't mean nothing is being returned to the client and still an HttpResponseMessage is generated.

Returning Domain Object
This is the simplest and easiest of all options. Here we treat our actions invocations as regular methods calls. We return domain objects from these actions. In this way, our actions' code is not populated with the HTTP based types. It is the framework's responsibility to create an HTTP response including the returned data as value.


It is for these actions, that framework hooks up the injected MediaTypeFormatter (s) and Content Negotiators based on the media types requested by client and type of data being returned. After data is passed through these stages, an HttpResponseMessage is generated and returned to the client.

Returning HttpResponseMessage Directly
This is another option allowed for Web API actions. Here the API takes the responsibility for creating the response on its own making it easier for the framework handling the response message. As a developer, we have the flexibility for controlling the HttpStatusCode generated with the response.


As you can see here, in addition to the data, we are specifying the HttpStatusCode for the returned response. We are using the value OK (= 200).

IHttpActionResult Interface & ASP.NET Web API 2
Here we are neither generating the domain objects directly nor we are handcrafting the HttpResponseMessage directly in ApiController's actions in a synchronous fashion. Instead, we are returning a response held by a type implementing IHttpActionResult interface. ASP.NET Web API 2 introduced IHttpActionResult in order to support asynchronous generation of HttpResponseMessage.



It also introduced a number of implementations of the interface in System.Web.Http.Results namespace in System.Web.Http assembly.



ApiController has also been updated with a number of additional methods returning such results. They make it easier for generating the response. They also include the appropriate HttpStatusCode with the response based on the method being used. These methods are supposed to be used from ApiController's actions to generate a response. The value obtained from these methods can simply be returned by the controller's action method.



The following is an example action supporting HTTP Post method. The action accepts student's data from the request body. After writing the data to the console, it generates an HTTP OK for the requesting client.


Let us see how our service responds to a request invoking the above action. In order to keep the example simple, the action is not doing much other than just writing the student's data to the console. It is also generating an OKResult (implements IHttpActionResult) by calling the Ok() method defined in ApiController type.



We can also provide custom implementation of the interface and use them in Web Api actions.

Returning Errors
The actions with return type as void or any other type other than HttpResponseMessage has only one way to return an error response i.e. to throw an exception in the event. The exception is caught by the framework pipeline and an appropriate error response is generated.



On the other hand the actions returning HttpResponseMessage can always generate error responses. Here we are using Request property of ApiController. This is of type HttpRequestMessage.


If this is a web client, the error is displayed in the browser as follows:



For the actions returning IHttpActionResult, we can always return different implementations of the interface based on the underlying condition. In case of error we may also use the methods added in ApiController for such conditions.

Wednesday, December 11, 2013

ASP.NET Web API 2 Content Negotiation & Media Type Formatting

ASP.NET Web API supports requests using HTTP methods. These requests can use any HTTP method including (but not limited to) GET and POST methods. The data to / from the service can use any media type as long as the service is supporting those formats. The client requests can specify the media type format using Accepts or Content-Type details of HTTP message. In the previous posts we discussed how ASP.NET Web API uses content negotiation to provide data to clients based on the requested format. There are some default media type formatters in ASP.NET Web API 2.

All of these MediaTypeFormatter(s) are available in System.Net.Http.Formatting assembly except ODataMediaTypeFormatter, which is available in System.Web.Http.OData assembly. All of them inherit from MediaTypeFormatter abstract base type.



MediaTypeFormatter has two abstract members. These methods are used to determine if a particular type can be formatted using the particular formatter. The methods return true if they support so. Here CanReadType is used when the service receives a request with content type as passed in the argument. On the other hand, CanWriteType is used when some data is to be pushed to client. Again the argument would refer to the data type of the object being pushed to the client.



Here the Read and Write methods in MediaTypeFormatter are asynchronous. BufferedMediaTypeFormatter provides a synchronous wrapper around these methods.

Pipe Delimited Formatter
Let's assume that our service needs to supports providing and accepting students' data in pipe delimited format. Now we need to add support to understand how to parse Student's data when provided by a client. We also need to convert the data pushed to our clients into pipe delimited format. ASP.NET Web API supports formatting data using MediaTypeFormatters. There are two such formatters added by default. They are to support XML and JSON data. If we are planning to support a new format, we need to add an explicit MediaTypeFormatter for such purpose. Here is a simpleton formatter to support pipe delimited data.


As you can notice from the above definition, the same formatter is used to read and write data by the service. Each formatter can be used to support a number of media types. They are identified through SupportedMediaTypes collection in MediaTypeFormatter. Our formatter is supposed to support pipe delimited text data, so the supported media type is specified as "text/pdv".

We must know that the same formatter is used both for reading and writing data by our service. The decision for supported types can be done in CanReadType / CanWriteType method pair. They are from the perspective of our service. Here CanReadType will be used for GET based requests when we need to push data to clients. On the other hand CanWriteType is used when service accepts some data from a client. In order for actual reading and writing of data for these types ReadFromStream and WriteToStream methods are used respectively.

Now we need to add the custom formatter to the list of Media Type Formatters used by the service. This is part of HttpConfiguration for the service. We can update WebApiConfig as follows:



Requesting Data for Configured Media Type Format
In the earlier posts we have seen how we can use Fiddler to request Web API to provide data in the format of the specified media type. We just need to use Accepts header. Here we are specifying the media type as "text/pdv".



Posting Data in Configured Media Type Format
Since our MediaTypeFormatter supports reading Student data in text/pdv format, we can post data to the service in this format. Let us add an action in our InstituteController. The action supports POST method of HTTP. Since we are using Attribute routing, we need to specify the route on the action.


We can compose the request using Fiddler. Here we are posting student's data in Pipe delimited format to the service.



Based on the content type specified in the request, the service picks up the correct MediaTypeFormatter. Since we are supporting data for Student type, the provided data is parsed into Student type format using ReadFromStream method of the formatter. The parsed object is then passed to the requested action as follows:



Download



Monday, December 2, 2013

Basic Routing in ASP.NET Web API 2

In the previous post, we discussed how we can create basic ASP.NET Web API based service and how we can request GET and POST requests to the service. In this post we would start exploring the routing a little further. In this example we will be building on top of the previous post introducing the idea of HTTP routes in ASP.NET Web API. You might need to download the code from previous post before starting following this.

HTTP Routes & Web API Configuration
The route configuration for ASP.NET Web API requests are specified in WebApiConfig. The route for the controller is specified as api/{Controller}. This is used to build routing table for Web API controllers. Using api should avoid any collision with ASP.NET MVC routes. It is a recommended convention. Here {controller} and {id} are placeholder variables. If there are no resource template in routing table matching the client request, the client receives a 404 message.



From client's Web API request, [x = {Controller}] would be mapped to xController. So in order to invoke StudentsController, we can specify the route as api/students. Updating a route configuration here, we can establish a different request format e.g. we can update it as api/MyControllers/{Controller} to require access configuration in the browser as follows:

http://localhost:60289/api/MyControllers/students

Since we are accessing the resource using web browser, it would be sending GET requests by default.



As we know that HTTP request methods are mapped to Web API controller actions. HTTP methods are also referred as VERBS. Accessing a Web API service as above with GET method would invoke parameterless Get...() method by default. Here we are returning all the students from the collection. The response displayed on the browser is in xml format. In the last post we discussed how we can request data in a different format (including json) from ASP.Net Web API service.



Parameterized GET using the Request URI
As you can see above, the controller also has a Get...() with a parameter of int type. This would be used when a resource is requested using api/{controller}/id. Here id is any integer value which is used to determine the StudentId from the collection for the requested student.



ASP.NET Web API also supports parameterized GET requests. In order to entertain such requests, we can introduce a number of Get...() methods in our APIController based on the expected requests. The default policy rule is that parameters with simple (DateTime, Decimal, Guid, String, and TimeSpan) & primitive types can be picked up from request URI. The parameters with complex types are picked up from request body (unlike MVC) after applying the required formatters as specified in Content-Type in HTTP message. In the following, we have introduced two new methods to StudentsController for supporting parameters for supporting requests with studentName parameter or studentId & studentName parameters.


The above methods can be used by Web API when a client sends a request as in the following image. You should notice that the order of parameters doesn't affect as long as the names of parameters are matching with the request.



The documentation seems to suggest that the API supports optional parameters for these actions. It must be remembered that the action selection is based on matching most number of parameters. This is useful if there are more than one method supporting the same HTTP methods (e.g. GET), the method invoked would be dependent on the matching of most method parameters from the request URI.

Action Names from Request URIs
As we have been discussing that the ASP.NET Web API actions are picked up from HTTP requests. We can also define resource templates in such a way that the actions are picked up from URIs as in ASP.NET MVC. Let us update the route configuration in WebApiConfig as follows:



Since actions are not being picked up from HTTP verbs anymore, a request URI without action info would result in a 404 message as follows:



As we discussed in the previous post, we can use fiddler to compose HTTP requests. Here we are composing a HTTP POST message. Just notice that we have POST action as part of the request URI.



This flexibility allows us to incorporate any arbitrary action in our Web API. Since URI contains action name, it is easier to use the specified method from a client. Make sure you decorate the action with the accepted HTTP method details. Here we are supporting GET for the specified action.


Here we are requesting the above action from Fiddler. As you can see we have specified info as action



The action name can be overridden by decorating the action method with ActionName attribute. Here Info is decorated with [ActionName("GetInfo")]. This action would be used for HTTP verbs including GET and HEAD. It must be remembered that since method names are used for external action requests, so, if we don't want to expose a method for external Web API requests then we must be decorating it with [NonAction] attribute as we have done for GetInfoForId method.


Request URI and Place Holders
As we have discussed above, we can define route templates with placeholders. Their values are picked up from client request. In the following example {controller}, {action} and {id} are placeholder variables.



We can specify further details of these placeholders in the route template for ASP.NET Web API service. We have already seen how we can mark these place holders as optional (e.g. id). Further details include specifying default values in case the request is missing them. It also supports constraints for these placeholders to restrict the values in the request. It seems that the default values can only be at the end of request URI. So in the above route template, we can define a default value for {id} place holder but we cannot define a default value for {controller} and {action} placeholders.

In the example below, we are defining a resource templates with default values and constraints for {action} placeholder. The request is restricted to have values including get, post, put and delete for this placeholder. If the request contains any other action, the client just get a 404 HTTP error message.



We are also specifying get as the default value of this placeholder if request is missing it.

Download

Wednesday, November 13, 2013

ASP.NET Web API based REST Service - An Introduction

ASP.NET Web API is a microsoft's framework for creating HTTP services that can reach a broad range of clients including browsers and mobile devices. In this post we are going to discuss how we can create a simple HTTP service using ASP.NET Web API and observe them using Fiddler.

Implementing ASP.Net Web API Service
We can create ASP.NET Web API projects using ASP.NET MVC project template. As soon as we select this type of project, we can select Web API in the second dialog shown for selection.



The services can also be added later as project items as follows:



The HTTP based rest services are implemented as Api Controllers in ASP.NET Web API. It is an object that handles HTTP requests. The service must inherit from ApiController in System.Web.Http namespace in System.Web.Http assembly.



As we discussed above, ASP.NET Web API suggests implementing HTTP based REST services as controllers. We can add a controller directly to Controllers folder in ASP.NET web API project. We can also use shortcut keys to bring up Add Controllers dialog.



Since we would be providing the complete definition ourselves, let's just add an empty MVC controller. You can see that we have added definitions of Get, Post, Put and Delete methods. These methods would be used by the framework as we received the corresponding GET, POST, PUT and DELETE http requests for the service. These names are based on conventions, alternatively we can decorate these methods with HttpGet, HttpPost, HttpPut and HttpDelete attributes from System.Web.Http namespace.



Now we update the contents of the file adding our definition of StudentsController.


Inspecting / Analyzing & Generating HTTP Requests
We can use Fiddler for debugging ASP.NET web api based HTTP services. Fiddler is a Telerik utility which is used to inspect, analyze and generate HTTP requests. It can also be used to compose HTTP request messages. After analyzing a request, we can update and replay the message.



ASP.NET Web API fully supports content negotiation out of the box. We can request data in the required format by specifying the details in the GET request. Here we have picked up a HTTP GET request in Fiddler. The request has the details about the content types supported by client browser.



Requesting Content in JSON format
We can very well compose the GET request in Fiddler to request data in a different format. As we have just stated that ASP.NET Web API fully supports content negotiation. We can also request data in a different format. In the following we are requesting data in text/json format using Fiddler.



The response from the API can be viewed in Fiddler. The above request results in the following response:



HTTP POST to ASP.NET Web API
We can also generated HTTP POST requests using Fiddler.Here we want to post some data in JSON format. We need to specify the content type to text/json in order for the service to correctly handle the data.



The request is received by ApiController in the method used for handling HTTP post requests. By convention, this is the method starting with name as Post. We can also decorate the methods with specific HttpPost attribute if we don't want to follow conventions.



Download