mohamad javad Taherian
mohamad javad Taherian

Reputation: 259

calling asp.net mvc 5 web api in asp.net core, FromBody always null

When I call the asp.net mvc 5 web api in Asp.net Core the input parameter FromBody always is null

asp.net Mvc 6 web api

public void Post([FromBody]string id)
{

}

calling web api in asp.net core

using (var client = new HttpClient())
  {
      string stringData = JsonConvert.
      SerializeObject("test");
      var contentData = new StringContent(stringData, System.Text.Encoding.UTF8,"application/json");
      HttpResponseMessage response1 = client.PostAsync("http://localhost:49741/api/values/", contentData).Result;      
  }

Upvotes: 0

Views: 2103

Answers (1)

Yaroslav
Yaroslav

Reputation: 534

As Crowcoder said. You should register MediaTypeFormatter. Here simple arctile how do that provides to do what you want.

But simpler is choose another way to work with incoming data. As application/json. Create simple Dto class like:

public class TestDataDto
{
    public string Id { get; set; }
}

And change argument type of your Post method:

// POST api/values
public void Post([FromBody]TestDataDto value)
{

}

Then code of your core client should be like this:

static void Main(string[] args)
{
    using (HttpClient httpClient = new HttpClient())
    {
        var someData = JsonConvert.SerializeObject(new { Id = "test" });
        var content = new StringContent(someData, System.Text.Encoding.UTF8, "application/json");

        var result = httpClient.PostAsync("http://localhost:55878/api/values", content).Result;
        if (result.IsSuccessStatusCode)
        {
            Console.WriteLine("All is fine");
        }
        else
        {
            Console.WriteLine($"Something was wrong. HttpStatus: {result.StatusCode}");
        }
    }

    Console.ReadKey();
}

Upvotes: 3

Related Questions