Friday, July 05, 2013

Web API Post with a String

I was trying for the longest time to get my first ASP.NET Web API project up and running with the simplest post.  I'm using Visual Studio 2012 with Web API 4 (along with the Web API Client Libraries nuget package).  My simplest get was working, but my post wasn't.

Here's my controller:

    public class ImportController : ApiController
    {

        public string Get()
        {
            return "hi mom";
        }

        public HttpResponseMessage Post( object s )
        {
            return new HttpResponseMessage( HttpStatusCode.Accepted );
        }

    }

Originally I had that parameter to the Post method as a string.  Then I tried to just post up using a simple HTML form with an input (text box) form element.  That didn't work.  Nor did this:

client.PostAsync( "http://localhost:52800/api/Import", new StringContent( "where my service at?" ) {  } ).ContinueWith( ( task ) =>
{
    Console.WriteLine( task.Result.StatusCode.ToString() );
    client.Dispose();
} );

Nor did anything else I tried.  I suppose the built-in deserializer just wouldn't match anything posted up to a string (nor scalar types I believe).  So after changing the parameter type to object and changing the client call from "PostAsync" to "PostAsJsonAsync" it worked.

Hope it can save someone some time.

No comments: