A simple POST request to Web API not hitting the API at all
21:20 29 Jun 2014

From my MVC application, I am trying to make a POST request to these sample end-points (actions) in an API controller named MembershipController:

[HttpPost]
public string GetFoo([FromBody]string foo)
{
    return string.Concat("This is foo: ", foo);
}

[HttpPost]
public string GetBar([FromBody]int bar)
{
    return string.Concat("This is bar: ", bar.ToString());
}

[HttpPost]
public IUser CreateNew([FromBody]NewUserAccountInfo newUserAccountInfo)
{
    return new User();
}

Here's the client code:

var num = new WebAPIClient().PostAsXmlAsync("api/membership/GetBar", 4).Result;

And here's the code for my WebAPIClient class:

public class WebAPIClient
{
    private string _baseUri = null;

    public WebAPIClient()
    {
        // TO DO: Make this configurable
        _baseUri = "http://localhost:54488/";
    }

    public async Task PostAsXmlAsync(string uri, T value)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(_baseUri);

            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));

            var requestUri = new Uri(client.BaseAddress, uri);

            var response = await client.PostAsXmlAsync(requestUri, value);

            response.EnsureSuccessStatusCode();

            var taskOfR = await response.Content.ReadAsAsync();

            return taskOfR;
        }
    }
}

I have the following default route defined for the Web API:

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }

UPDATE My code breaks into the debugger until the time the PostAsXmlAsync method on the System.Net.HttpClient code is called. However, no request shows up in Fiddler.

However, if I try to compose a POST request in Fiddler or try to fire a GET request via the browser to one of the API end-points, the POST request composed via Fiddler tells me that I am not sending any data and that I must. The browser sent GET request rightly tells me that the action does not support a GET request.

It just seems like the System.Net.HttpClient class is not sending the POST request properly.

asp.net asp.net-mvc asp.net-web-api dotnet-httpclient