Search code examples
c#asp.net-coreasp.net-web-apihttpclientrestsharp

Call WebApi Endpoint Passing in Object


I have the following endpoint

[HttpPost]
[DisableRequestSizeLimit]
[RequestFormLimits(KeyLengthLimit = int.MaxValue)]
public IActionResult PostData([FromForm]Data data)

The Data class looks like this

public class Data
{
    public string A { get; set; }
    public string B { get; set; }
}

I am calling this endpoint in this way

var url = ...;

var client = new HttpClient();
var data = new
{
    a = "Foo",
    b = "Bar"
};
var result = await client.PostAsJsonAsync(url, data);

But the data parameter in the PostData method always is null. Any ideas what I am doing wrong?


Solution

  • If your content type is application/json use [FromBody] instead of [FromForm].