Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HttpPost from PostAsync always null

I'm about to go nuts trying to figure out how to pass POST parameters to Web API methods in ASPNET CORE 2.0.

I have a C# client application and a C# server application.

  • I've tried using [FromBody] on the Web Api method.
  • I've tried setting the content type to "application/json"
  • I've simplified my controller action to be as basic as possible
  • I have tried passing both a string and a complex object.

It's ALWAYS NULL. What is going on?

Client code:

private static async Task SendCustomObject()
{
    var controllerName = "BasicApi";
    var basicClientApi = string.Format("http://localhost:5100/api/{0}", controllerName);

    using (var httpClient = new HttpClient()){

        var packetData = new TestPacket();
        var jsonObj = new { json = packetData };
        JObject jobject = JObject.FromObject(packetData);

        var json = JsonConvert.SerializeObject(jobject);
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        // This doesn't help:
        //httpClient.DefaultRequestHeaders.Accept.Clear();
        //httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

        var response = await httpClient.PostAsync(basicClientApi, content);                    

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var rawResponse = await response.Content.ReadAsStringAsync();                        

            JObject o = JObject.Parse(rawResponse);
            Console.WriteLine(o.ToString());    
        }
    }
}

Server code:

namespace myApp.Controllers
{
    [Route("api/[controller]")]
    public class BasicApiController : Controller
    {    

      [HttpPost]    
      public JsonResult Post([FromBody] string json) // json is always null!
      {                

        var jsonData = JsonConvert.DeserializeObject<Models.TestPacket>(json);
        return Json(new { result = true });

      }
    }
 }
like image 726
demifiend Avatar asked Jul 01 '26 16:07

demifiend


1 Answers

ASP.NET Core default binder de-serializes the models for you, you don't need to do it by hand. Specifically, you cannot treat an object as if it was a string.

Look at this much simpler example:

private static async Task SendCustomObject()
{
    var controllerName = "BasicApi";
    var basicClientApi = string.Format("http://localhost:5100/api/{0}", controllerName);

    using (var httpClient = new HttpClient()){

        var packetData = new TestPacket();
        var jsonObj = new { json = packetData };

        var json = JsonConvert.SerializeObject(jsonObj); // no need to call `JObject.FromObject`
        var content = new StringContent(json, Encoding.UTF8, "application/json");
        content.Headers.ContentType = new MediaTypeHeaderValue("application/json");

        var response = await httpClient.PostAsync(basicClientApi, content);                    

        if (!response.IsSuccessStatusCode)
        {
            Console.WriteLine(response.StatusCode);
        }
        else
        {
            var rawResponse = await response.Content.ReadAsStringAsync();                        

            JObject o = JObject.Parse(rawResponse);
            Console.WriteLine(o.ToString());    
        }
    }
}

namespace myApp.Controllers
{
    [Route("api/[controller]")]
    public class BasicApiController : Controller
    {    

      [HttpPost]    
      // don't ask for a string, ask for the model you are expecting to recieve
      public JsonResult Post(Models.TestPacket json)
      {                
           return Json(new { result = true });
      }
    }
 }
like image 170
Camilo Terevinto Avatar answered Jul 03 '26 06:07

Camilo Terevinto