Can I have both FromForm and FromBody attributes to action ?
public IActionResult Index([FromBody][FromForm] Person model){
.....
}
Can I have both FromForm and FromBody attributes to action ?
public IActionResult Index([FromBody][FromForm] Person model){
.....
}
No, it's not possible.
The FromForm
attribute is for incoming data from a submitted form sent by the content type application/x-www-form-urlencoded
while the FromBody
will parse the model the default way, which in most cases are sent by the content type application/json
, from the request body.
Please look at this library https://github.com/shamork/Toycloud.AspNetCore.Mvc.ModelBinding.BodyAndFormBinding
I used the source and modified a bit as there is an issue with .Net 5 with ComplexTypeModelBinderProvider being obsolete
In short, this prevents having to do this
public class JsonRequestItem {
public string jsonRequest { get; set; }
}
[HttpPost]
[ActionName("NewRequest")]
[Consumes("application/json")]
public IActionResult NewRequestFromBody([FromBody]JsonRequestItem item) {
return NewRequest(item.jsonRequest);
}
[HttpPost]
[ActionName("NewRequest")]
[Consumes("application/x-www-form-urlencoded")]
public IActionResult NewRequestFromForm([FromForm]JsonRequestItem item) {
return NewRequest(item.jsonRequest);
}
private IActionResult NewRequest(string jsonRequest) {
return new EmptyResult(); // example
}
Now you can simplify as one action and get both FromBody and FromForm
[HttpPost]
[ActionName("NewRequest")]
public IActionResult NewRequestFromBodyOrDefault([FromBodyOrDefault]JsonRequestItem item) {
return new EmptyResult(); // example
}