Posts Tagged 'SOA'

Creating a Custom Web API Model Binder

When the Web API accepts a request from a client to a service, the Web API attempts to map the data in the request to a .NET object to pass as a parameter to the appropriate method in the service–a process called model binding. I’m consistently amazed at how powerful model binding is. But, as powerful as the process is, it is possible to have a request that defeats model binding. Fortunately, that doesn’t mean that you’re defeated: you can create your own model binder that will map the data in an incoming request to the .NET object that your service method accepts as a parameter.

As an example for creating a model binder, I first need a request that defeats the default model binder–not easy to do because the model binder is so powerful. So, I cheated: I created an ASP.NET WebForm with three TextBoxes (with IDs of CustomerID, CompanyName, and City), a Label (ID of Messages), and a GridView (GridView1). I then posted that whole form to a Web API service using a JavaScript function attached to the OnClientClick event of an ASP.NET Button on the WebForm:

<asp:Button ID="PostButton" runat="server" Text="Update" OnClientClick="return UpdateCustomer();" />

The JavaScript function serializes the form and posts it to a Web API method at “<server/site name>/CustomerManagement” (the function returns false to prevent the ASP.NET Button from posting the form back to the server):

function UpdateCustomer() {
    $.post('CustomerManagement', $('#form1').serialize())
     .success(function (data, status) {
     .error(function (data, msg, detail) {
        alert(data + '\n' + msg + '\n' + detail)
   return false;

I defined the the Web API method that will process the request to accept the request’s values in the properties of a class I created and called CustomerOrderDTO:

public HttpResponseMessage Post(CustomerOrderDTO custOrderDTO)

And here’s the first version of that CustomerOrderDTO class  with properties whose names match the Ids on the TextBoxes:

public class CustomerOrderDTO
  public string CustomerID { get; set; }
  public string CompanyName { get; set; }
  public string City { get; set; }

And, amazingly, this works! Model binding instantiates a CustomerOrderDTO object and fills the properties on the object with the matching values from the TextBoxes on the form. But what about the GridView in my WebForm?

Defeating the Default Model Binder

The first thing to recognize is that, normally, the data on the GridView isn’t sent in the request to the Service when I use the serialize method in my JavaScript function: in Display mode, the GridView is just text in an HTML table which the serialize method ignores. However, if the user puts a row in the GridView into Edit mode, the values in the row are displayed in TextBoxes–and the values from those TextBoxes are included in the serialized request sent to the service.

What I would like is to use a DTO class like the following, where I want the OrderId, OrderDate, and RequiredDate properties to hold the values from the row in the GridView that the user has put in Edit mode:

public class CustomerOrderDTO
  public string CustomerID { get; set; }
  public string CompanyName { get; set; }
  public string City { get; set; }
  public string OrderId {get; set;}
  public DateTime OrderDate { get; set; }
  public DateTime RequiredDate { get; set; }        

The model binder can’t do that and looking into the request shows why. The content of the request sent by my JavaScript code looks something like this (the ellipses mark parts of the request that I’ve omitted to focus on what matters to this example):


If you look carefully you can see the TextBoxes’ names with their values in the request, with each name/value pair separated by an equals sign and ending with an ampersand (e.g. CustomerID=ALFKI&CompanyName=…). You can also find the values from the row of the GridView that’s being sent to the service with its TextBoxes’ names and their values though those names and values aren’t as obvious:


The GridView’s TextBoxes have names that are auto-generated by the GridView control and look like “GridView1%24ctl05%24ctl02” (that’s the name of TextBox in the fifth row, second column). These names, in addition to being opaque, will change depending on which row the user has put in Edit mode (for instance, the equivalent TextBox from the fourth row has the name GridView1%24ctl04%24ctl02). The default model binding provided with the Web API can’t match those changing names to properties on a class. However, if I create my own model binder, I can make this work.

Creating a Custom Model Binder

The first step in creating a custom model binder is to add a class to your project and have the class implement the IModelBinder interface (for the following code to work, you’ll need using statements for System.Web.Http.Controllers, System.Web.Http.ModelBinding, System.Web.Http.ValueProviders, and System.Net). The interface will give add a single method to your model binding class, called BindModel:

public class CustomerOrderModelBinder: IModelBinder
  public bool BindModel(System.Web.Http.Controllers.HttpActionContext actionContext, ModelBindingContext bindingContext)

The BindModel method will be called by the Web API as it attempts to map the incoming request to my CustomerOrderDTO object (or will called be after I do a little more work–see the end of this post). The two parameters passed to the BindModel method give you access to all the data that you might need to retrieve the values in the request and move them to the object that your service method is accepting–but I’ll use very little of those features in this example. There are also a couple of ways that you can, after extracting values from the request sent to the service, pass those values to the service’s method. For this example, I’ll just instantiate my CustomerOrderDTO object and put it into the Model property of the ModelBindingContext object that’s passed as a parameter to the BindModel method as the first steps in my BindModel code:

CustomerOrderDTO coDto = new CustomerOrderDTO();
bindingContext.Model = coDto;

My next step is extract the values from the request by reading the content of the request from the HttpActionContext object and storing it in a string. Then I find the start of my data by looking for the name of the first TextBox in the form (CustomerID) and splitting the following text wherever an ampersand appears–that will give me an array of name/value pairs (e.g. “CustomerID=ALFKI”):

string ct = actionContext.Request.Content.ReadAsStringAsync().Result;
ct = ct.Substring(ct.IndexOf("CustomerID"));
string[] vals = ct.Split('&');

I can now use LINQ statements to pull the name/value pairs that I want out of this array. Once I do that, I can extract the data that I want by looking for the equals sign that separates the name from the value. However, if the values contain “sensitive” characters (like forward slashes, spaces, or ampersands) those values will be URL encoded: A date like “1/15/1998 1:20:05 AM”, for instance, will turn up in the request’s content as the value “1%2F15%2F1998+1%3A20%3A05+AM.” I can use the WebUtility’s UrlDecode method to convert those encoded values back into their original characters.

So, to set the CustomerID property on my object, I use this code:

coDto.CustomerID = (from val in vals
                    where val.StartsWith("CustomerID")
                    select WebUtility.UrlDecode(val.Substring(val.IndexOf('=') + 1))).First();

Extracting the three GridView values is only slightly more difficult. One of the constants in the names of those TextBoxes is that they all begin with the name of the GridView they’re part of (GridView1 in my example). I use that to create another collection of just the name/value pairs belonging to the GridView:

var res = (from val in vals
           where val.StartsWith("GridView1")
           select val).ToList();

Then it’s just a matter of finding the value following the equals sign for each item in the collection, decoding the value,  doing a type conversion (for the dates), and putting the result in the appropriate property. Here’s the code for setting the OrderDate property the previous code will have put in the third position of the collection:

coDto.OrderDate = DateTime.Parse(WebUtility.UrlDecode(res[2].Substring(res[2].IndexOf('=') + 1)));

After moving all the values you can find into your object’s property, your method should return true to indicate successful processing.

Invoking the Model Binder

But there’s still a little work required to have the Web API use your custom model binder. First you need to create a factory object that will instantiate your model binder and return it. That’s just a class that inherits from ModelBinderProvider. Override its GetBinder method and, in the method, create your binder and return it:

public class CustomerOrderModelBinderProvider : ModelBinderProvider
  public override IModelBinder GetBinder(System.Web.Http.HttpConfiguration configuration, Type modelType)
   return new CustomerOrderModelBinder();

The parameters passed to the GetBinder method allow you to create more complex logic here to choose among binders if you need to–but, again, I don’t need them for this example.

The last step is to tell the Web API when to use your factory. The most obvious way is to use the ModelBinder attribute on the parameter passed to my Post method. You just need to pass the attribute the type of your binder factory object (you’ll need a using statement for System.Web.Http.ModelBinding for this code to work). This mechanism assumes that I only want to use this model binder for this particular method:

public HttpResponseMessage Post([ModelBinder(typeof(CustomerOrderModelBinderProvider))]CustomerOrderDTO custOrderDTO)

You can also use the ModelBinder attribute on the DTO class itself if you want to use this custom model binder every time you use the class:

public class CustomerOrderDTO

This is a very bare bones, brute-force-and-ignorance model binder that doesn’t take advantage of much of the power built into the model binding framework. For instance, if I knew the names of my TextBoxes (something not possible with the GridView’s constantly changing names) I might have been able to use the GetValue method on the ValueProvider property of the ModelBindingContext to extract the values from the request; the HttpActionContext’s GetValidators method would allow me to execute any validation attributes applied to the properties on my object; if my conversions failed (or I couldn’t find any values), I should use the AddModelError method on the ModelState property of the HttpActionContext object to pass error messages to the service’s methods along with the DTO. However, all I wanted to demonstrate was that it’s possible to bind almost anything sent to your service to the resulting object: I figure if you can bind this WebForm, you can bind anything.

Peter Vogel

Processing Messages in a Self-Hosted Web API Service

In an earlier post, I showed how to host an ASP.NET Web API service on a server without IIS. In that post, I suggested that the most interesting object used in the self-hosting process is the HttpSelfHostConfiguration object–that’s the object that allows you to configure your service. In that last post, for instance, I used the HttpSelfHostConfiguration object to specify the service’s URL and routing rules. But that’s just a taste of the configuration object’s power: you can also use the HttpSelfHostConfiguration object to insert handlers into the Web API’s processing pipeline to centralize  pre- or post-processing on messages sent to and from your service (you can insert message handlers when hosting a Web API service in IIS, also).

You can add as many handlers as you want to the Web API processing pipeline: each handler’s output is automatically passed to the next handler in the pipeline. The handlers are processed in reverse order to the way that you add them to the pipeline (i.e. the handler you add first is the handler “closest” to your service and gets inbound messages after all the other handlers you add have processed the message; for the same reason, the first handler you add will see any outbound messages as soon as they leave the service and before any of the handlers you’ve added to the pipeline see the message).

As an example, let’s say that you don’t want the services your hosting to process any messages with the HTTP Delete verb because you don’t allow deletes: you simply mark records as deleted and stop returning those records to the client. All requests to delete records should, you’ve decided, be sent with the HTTP Put verb because they’re actually updates to the record’s Deleted field. You could, of course, simply not provide a Delete method in your service–that would generate a return error message of “The requested resource does not support http method ‘GET’.” should someone send your service a Delete request. However, you may want to send a response that’s more informative to any client using the Delete verb (alternatively, you might want to log these Delete requests). You could add a Delete method to each of your services that performed those actions but it would be a better practice to centralize that site-wide utility code in one place: a message handler.

Adding Handlers

The first step is to add your message handler to the configuration object’s Handlers collection before passing the configuration object to the host. This code assumes that the handler is called PHVHandler:

hcfg = new HttpSelfHostConfiguration("");
PHVHandler hndlr = new PHVHandler();

If you want, you can limit a handler to processing only those requests for a single route. In that case, you pass the handler as the fifth parameter to the MapHttpRoute method (right after specifying any constraints on the route). This example adds a handler that will be used only for requests with “Customers” in the URL:

hcfg = new HttpSelfHostConfiguration("");
PHVHandler hndlr = new PHVHandler();
                         new { controller = "CustomerManagement" },

Creating a Handler

A handler is a class that inherits from DelegatingHandler (you’ll need using statements for  System.Net and System.Net.Http for the following code to work). Once you’ve added the class you must override its SendAsync method. The SendAsync method is called automatically by the Web API for every request to your service. The method is passed an HttpRequestMessage that holds all the data related to the request to your service (and a CancellationToken, which I’ll ignore in this post):

class PHVHandler: DelegatingHandler
 protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

If the PHVHandler is the last one added to the pipeline, it will get the HttpRequestMessage before any other handler has modified it; if other handlers were add to the configuration object after this handler, then the HttpRequestMessage will show the results of any modifications that handlers earlier in the pipeline have made. If you’re doing test driven development, by the way, you can test your handler by instantiating an HttpRequestMessage object, setting its properties, and passing it your method–something that’s virtually impossible to do with the ASP.NET HttpContext object.

Your message processing code goes in the SendAsync method. The following code checks to see if the Method (the HTTP verb) associated with this request is a Delete and, if so, stops the message from proceeding up the pipeline. To short-circuit processing and return a message to the client you need to create two objects: an HttpResponseMessage object, specifying a return value with some content (Forbidden and a string, , in this case) and a TaskCompletionSource (because these are asynchronous methods, Task-related objects are used to wrap most of the method’s inputs and outputs). With the two objects created, use the TaskCompletionSource object’s SetResult method to pass the HttpResponseMessage to the TaskCompletionSource. Once the TaskCompletionSource is configured, you can return it which is what this code does:

if (request.Method == HttpMethod.Delete)
  HttpResponseMessage rsp = new HttpResponseMessage(HttpStatusCode.Forbidden);
  rsp.Content =new StringContent("Deletes not accepted--use Put"); 
  TaskCompletionSource<HttpResponseMessage> tkc = new TaskCompletionSource<HttpResponseMessage>();
  return tkc.Task;

However, if the message sent to your service isn’t using the Delete verb, it should be passed on to your service (or the next handler in the pipeline) for processing. To pass the message on up the pipeline, call the base version of the SendAsync method, passing the parameters you originally received in your version of the method:

return base.SendAsync(request, cancellationToken);

Calling the SendAsync method puts the message in the pipeline to go to the service. When your service finishes processing the message, the service will create a response message and send that back down through the pipeline. The object returned by the SendAsync method  in the previous code is the outbound response message created by the service (and, possibly, modified by any message handlers that the message has already passed through). You must return the result of the SendAsync method from your method to allow the message to continue through the pipeline back to the client. While it’s not obvious in this code, the SendAsync method is returning a Task object holding an HttpResponseMessage containing the service’s output message (again, the Task object is required to support asynchronous processing).

Altering the Inbound Message

However, a message handler can do more than just terminate processing. You can use a message handler to alter the message on its way up the pipeline. Rather than terminate processing when you see a Delete verb, for instance, you could change all Delete requests to Puts and let the messages continue on up the pipeline. As in the previous example, the following code first checks the inbound message to see if it’s a Delete. If it is, the code then alters the message before sending it on through the pipeline using the SendAsync method. The SendAsync method will (eventually, since its an asynchronous method) return the Task object holding the client’s HttpResponseMessage which you must return from your method:

if (request.Method == HttpMethod.Put)
 request.Method = HttpMethod.Put;
 return base.SendAsync(request, cancellationToken);

Altering the Outbound Message

Because the message passes through your handler on the way back to the client, you can also process the outbound message after it leaves the service and before it gets back to the client. This means waiting for your call to the base.SendAsync method to complete so that you can catch the outbound message–not a completely trivial task because SendAsync is an asynchronous method. If you’re working in .NET 4.0 then you’ll need to use the ContinueWith method to wait for the Task object returned from the SendAsync method. The ContinueWith method passes the Task returned from SendAsync to a lamba expression of your design. In that lambda expression you’ll typically want to extract the HttpResponseMessage from the Task and modify the message before letting the message continue through the pipeline. This example sets the StatusCode on the message to indicate that the request needs to be upgraded before returning the response (the Web API will take of wrapping the response in a Task):

return base.SendAsync(request, cancellationToken).ContinueWith((t) =>
  HttpResponseMessage rsp = t.Result;
  rsp.StatusCode = HttpStatusCode.UpgradeRequired;
  return rsp;

In .NET 4.5 you can take advantage of the await keyword which simplifies working with asynchronous methods–your code hardly looks asynchronous at all! First, you must add the async keyword to your method’s declaration:

class PHVHandler: DelegatingHandler
 async protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)

With the async keyword in place, you can use the await keyword to catch the output of the SendAsync method when it’s finally handed back to you. This example, as before, sets the StatusCode on the response message before returning the response:

HttpResponseMessage rsp = await base.SendAsync(request, cancellationToken);
rsp.StatusCode = HttpStatusCode.UpgradeRequired;
return rsp;

As you may have noticed, one of the nice features of self-hosting is that all your configuration code goes in one place: In the Windows Service that you’ll use to host your Web API service–which I find sort of convenient. I referred to Learning Tree’s course on creating .NET services (including the ASP.NET Web API) in my last post but I should also have mentioned Learning Tree’s course on deciding what services you need and how they should work together, Service-Oriented Architecture (SOA): A Comprehensive Hands-On Introduction (especially because I wrote the course).

Peter Vogel

Learning Tree International

.NET & Visual Studio Courses

Learning Tree offers over 210 IT training and Management courses, including a full curriculum of .NET training courses.

Free White Papers

Questions on current IT or Management topics? Access our Complete Online Resource Library of over 65 White Papers, Articles and Podcasts

Enter your email address to subscribe to this blog and receive notifications of new posts by e-mail.

Join 29 other followers

Follow Learning Tree on Twitter


Do you need a customized .NET training solution delivered at your facility?

Last year Learning Tree held nearly 2,500 on-site training events worldwide. To find out more about hosting one at your location, click here for a free consultation.
Live, online training

%d bloggers like this: