What the difference between [FromForm] and [FromBody] in Asp.Net Core. I will use one of them for post method. If I use FromForm, can it occur be a security problem?
Using [FromBody] When a parameter has [FromBody], Web API uses the Content-Type header to select a formatter. In this example, the content type is "application/json" and the request body is a raw JSON string (not a JSON object). At most one parameter is allowed to read from the message body.
The [FromUri] attribute is prefixed to the parameter to specify that the value should be read from the URI of the request, and the [FromBody] attribute is used to specify that the value should be read from the body of the request.
Please note that we are able to send [FromBody] parameter in HTTP GET Request input.
Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.
The FromForm
attribute is for incoming data from a submitted form sent by the content type application/x-www-url-formencoded
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.
For security problem , you could use ValidateAntiForgeryToken
Attribute for post method which specifies that the class or method that this attribute is applied validates the anti-forgery token. If the anti-forgery token is not available, or if the token is invalid, the validation will fail and the action method will not execute.
The anti-forgery token found in MVC is a way to prevent cross site request forgery (CSRF) attacks. Without going into too much detail, a CSRF attack occurs when a user visits an untrusted site and enters some information that is then posted back to a site to which the user has already authenticated.
You could refer to the following link on how AntiForgeryToken() actually works:
http://blog.at-dot.net/archive/2014/05/13/mvc-what-is-html-dot-antiforgerytoken-and-how-does-it-actually-work/#targetText=The%20anti%2Dforgery%20token%20found,the%20user%20has%20already%20authenticated.
FromBody (ContentType: application/json):
{ "user" : "conejo", "password" : "panda" }
FromForm (ContentType: application/x-www-url-formencoded):
user=conejo&password=panda
Take into account that to send more than one field using FromBody you would have to wrap them in an object. As per se, FromForm is not less secure than FromBody. Vulnerabilities mainly come from not using HTTPS
If you look in the Microsoft documentation
Microsoft documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With