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?

4
  • 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 Commented Nov 1, 2019 at 14:03
  • FromForm? but posting as JSON. Not form was went Commented Nov 1, 2019 at 14:04
  • FromForm that - forms don't use JSON - JSON was invented at least a decade later. Use a FormUrlEncodedContent instace with PostAsync. All it needs as input is anything that implements IEnumerable<System.Collections.Generic.KeyValuePair<string,string>> like a Dictionary<string,string> Commented Nov 1, 2019 at 14:06
  • On the other hand, if that PostData method isn't used with forms, you could just remove [FromForm] Commented Nov 1, 2019 at 14:08

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

7 Comments

Now the PostData method does not fire at all.
Have you changed the ContentType to application/json?
You may also want to remove the RequestFormLimits attribute from the method as well.
Ok will do but I put that there because I will be passing quite large data.
Do I set the content type on the DefaultRequestHeaders?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.