Archive | Coding RSS feed for this section

Posting Strongly Typed Models to an ASP.NET WebAPI From C#

I’m currently converting an existing WCF service into an ASP.NET Web API service for one of my personal projects.

In my case I need to call an http post method with an instance of a model object. With a WCF service you can add a service reference and visual studio will generate a client proxy. With plain http based services you cannot do this because there is no metadata exposed.

I’ve grown accustomed to the convenience of a strongly typed client proxy. There are many examples of how to do this using a javascript client but I needed to do this from a C# client.

For those in a similar position, here is how I got this to work:


My contrived example will expose a http post operation on a PersonApiController and accept a Person object to be posed to it.

Create a model object which can be referenced by both the client and service projects. Note that we’ve marked up the class with DataContract and DataMember attributes. This is required for the ASP.NET model binding to work.

public class Person {

    public int Id { get; set; }

    public string FirstName { get; set; }

    public string LastName { get; set; }


In your api controller, create a method which takes your model type as a parameter:

public class PersonController : ApiController {

    public void Post(Person person) {
        // do your work here.


On the client, you can do something like this:

// create new model object. 
Person personToCreate = new Person { 
    FirstName = "Jon", 
    LastName = "Snow" 

// serialize to json string. 
string req = JsonConvert.SerializeObject(personToCreate);

using (var client = new HttpClient()) { 
    client.BaseAddress = new Uri("http://localhost:3756/");

    // do post.
    HttpResponseMessage response = client.PostAsync("api/Person", new StringContent(req, Encoding.Default, "application/json")).Result;
    if (!response.IsSuccessStatusCode) {
        // error!

When you hit the service call in the debugger, you can see that the ASP.NET model binding has received the json person object and deserialised it for you:


If you would like to send a response or return error codes to your client, you can extend out your method a bit like so:

public HttpResponseMessage Post(Person person) { 

    try { 
        // do your work here.
        string jsonResponse = ""; // your response here.

        HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK) {
            Content = new StringContent(jsonResponse, Encoding.Default, "application/json")
        return result;

    } catch (Exception ex) {
        return Request.CreateErrorResponse(HttpStatusCode.Forbidden, ex);


I hope this helps.

Comments { 0 }