Joe
Joe

Reputation: 5487

Model Binder Not Finding Post Data

I have a simple jquery post

function saveImage(base64) {
  $.post("http://localhost:50575/api/images", {base64Data: base64});
}

That is going against a .net core controller

[HttpPost]
public async Task<ActionResult> Post(string base64Data)
{
    var base64 = Request.Form["base64Data"];
    return Ok();
}

When the data is posted, base64Data is null. However, base64, which is populated from the form variables has a value.

Is there any reason why this shouldn't work?

Upvotes: 0

Views: 80

Answers (1)

itminus
itminus

Reputation: 25350

What sent by $.post("http://localhost:50575/api/images", {base64Data: base64}) is:

POST /api/images HTTP/1.1
Content-Type: application/x-www-form-urlencoded

base64Data=xxxxxxxx

Since you send the request with a content-type of application/x-www-form-urlencoded and have the request processed by a ApiController , you should decorate the parameter with a [FromForm]

public async Task<ActionResult> Post([FromForm] string base64Data)
{
    // ...
}

Or if you would like to send the request encoded with application/json , you should firstly create a DTO to hold the whole playload :

public class Base64Dto{
    public string Base64Data{get;set;}
}

and decorate the parameter with a [FromBody] at the same time :

public async Task<ActionResult> Post([FromBody] Base64Dto base64Data)
{
    // var base64 = Request.Form["base64Data"];
    return Ok();
}

Another way to hold the whole payload with Base64Dto , is to send the request with a header of Content-Type: application/x-www-form-urlencoded , and use a [FromForm] attribute at the same time :

public async Task<ActionResult> Post([FromForm] Base64Dto base64Data)
{
    // var base64 = Request.Form["base64Data"];
    return Ok();
}

Upvotes: 1

Related Questions