'httpclient call to webapi to post data not working

I need to make a simple webapi call to post method with string argument.

Below is the code I'm trying, but when the breakpoint is hit on the webapi method, the received value is null.

StringContent stringContent = new System.Net.Http.StringContent("{ \"firstName\": \"John\" }", System.Text.Encoding.UTF8, "application/json");
HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsync(url.ToString(), stringContent);

and server side code:

 // POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}

please help...



Solution 1:[1]

Alternative answer: You can leave your input parameter as string

[HttpPost]
public void Post([FromBody]string value)
{
}

, and call it with the C# httpClient as follows:

var kvpList = new List<KeyValuePair<string, string>>
{
    new KeyValuePair<string, string>("", "yo! r u dtf?")
};
FormUrlEncodedContent rqstBody = new FormUrlEncodedContent(kvpList);


string baseUrl = "http://localhost:60123"; //or "http://SERVERNAME/AppName"
string C_URL_API = baseUrl + "/api/values";
using (var httpClient = new HttpClient())
{
    try
    {   
        HttpResponseMessage resp = await httpClient.PostAsync(C_URL_API, rqstBody); //rqstBody is HttpContent
        if (resp != null && resp.Content != null) {
            var result = await resp.Content.ReadAsStringAsync();
            //do whatevs with result
        } else
            //nothing returned.
    }
    catch (Exception ex)
    {
        Console.ForegroundColor = ConsoleColor.Red;
        Console.WriteLine(ex.Message);
        Console.ResetColor();
    }
}

Solution 2:[2]

For the record I tried the above and could not get it working!

I couldn't get it working because my API was in a separate project. Which is fine right? no, I was doing Dependency Injection into the controller while using the Startup class against the Base project.

You can resolve this by using the WebAPI's config and configuring Dependency Injection there with Unity. The below code works for me:

WebApiConfig.cs:

 public static void Register(HttpConfiguration config)
        {
            config.MapHttpAttributeRoutes();

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

            RegisterUnity();
        }

        private static void RegisterUnity()
        {
            var container = new UnityContainer();

            container.RegisterType<IIdentityRespository, IdentityRespository>();

            GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
        }
    }

I hope it helps others :-)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 joedotnot
Solution 2 Lee