1

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?

Sachin Kainth
  • 45,256
  • 81
  • 201
  • 304
  • 1
    That's not an `out` parameter so what does `comes back` mean? `result` won't be null either, it will always contain the response – Panagiotis Kanavos Nov 01 '19 at 14:03
  • `FromForm`? but posting as JSON. Not form was went – Nkosi Nov 01 '19 at 14:04
  • `FromForm` that - forms don't use JSON - JSON was invented at least a decade later. Use a [FormUrlEncodedContent](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.formurlencodedcontent?view=netcore-3.0) instace with `PostAsync`. All it needs as input is anything that implements `IEnumerable>` like a `Dictionary` – Panagiotis Kanavos Nov 01 '19 at 14:06
  • On the other hand, if that `PostData` method isn't used with forms, you could just remove `[FromForm]` – Panagiotis Kanavos Nov 01 '19 at 14:08

1 Answers1

2

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

TrevorBrooks
  • 3,590
  • 3
  • 31
  • 53