29

Can I have both FromForm and FromBody attributes to action ?

public IActionResult Index([FromBody][FromForm] Person model){
.....
}
Petko Pasev
  • 317
  • 1
  • 3
  • 6
  • When someone send request from postman and have provided the data in raw section to be mapped to the model but in the same time to work with forms. – Petko Pasev May 21 '18 at 19:39
  • 2
    Look it https://stackoverflow.com/questions/50245160 There is a way to solve your task. – Nodon Aug 28 '18 at 12:50

2 Answers2

44

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.

Marcus Höglund
  • 16,172
  • 11
  • 47
  • 69
6

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

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.binders.complextypemodelbinderprovider?view=aspnetcore-5.0

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
    }
John Reaume
  • 61
  • 1
  • 1