Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to DRY [FromBody] attribute and default content-negotiation in ASP.NET Core MVC on all post actions?

We have more than a thousand HTTP services across 50 applications all of which use HttpPost for operations that change server's state. We use Fiddler to test each service we create and two boilerplate piece of code is always bothering us and prevent smooth coding.

  1. All models (reference types) should have [FromBody] attribute in order to be bound to HTTP Request's body
  2. Each time we should include Content-Type: application/json in our HTTP Requests for content-negotiation.

Since more than 99 percent of our services use JSON in body for POST operations that need a model to be bound, how can we DRY these two pieces of code in ASP.NET Core MVC? In other words, how to tell ASP.NET Core MVC that always perform [FromBody] for reference types if the HTTP method is POST, and how to instruct it to use only JSON content-negotiation for HTTP Request's body?

like image 993
mohammad rostami siahgeli Avatar asked Dec 17 '17 05:12

mohammad rostami siahgeli


1 Answers

Short answer: use [ApiControllerAttribute], but it has some other limitations and features.

Starting with asp.net core mvc 2.1 you can decorate your specific controller, base controller or an entire assembly with the attribute [ApiControllerAttribute]. It alters the behavior of your controller in many ways, one of which is exactly what you need: the binding will look into the body by default, so you don't need to specify [FromBody] on each Action. Be aware that it adds some other features that you may or may not need:

  • Attribute routing requirement: you will need to specify routing using attributes on all the controllers decorated with the [ApiControllerAttribute].

  • Automatic HTTP 400 responses: that's it automatic model validation before your action is called.

  • Multipart/form-data request inference when decorating your action with [FromForm].

  • Problem details for error status codes: more detailed information is returned together with the status code.

However, all those features (other than attribute routing) are not hard enforced and can be changed as you need.

More information here: https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-3.0#multipartform-data-request-inference and here: https://www.strathweb.com/2018/02/exploring-the-apicontrollerattribute-and-its-features-for-asp-net-core-mvc-2-1/

like image 115
Barsik Avatar answered Sep 23 '22 10:09

Barsik