When I create a new controller in the API project, it generates a controller class with [ApiController]
attribute, like this:
[ApiController]
public class TestController : ControllerBase
{
//implementation
}
I've seen a few webapi projects where usage of this attribute is omitted. Microsoft documentation here says:
Indicates that a type and all derived types are used to serve HTTP API responses. The presence of this attribute can be used to target conventions, filters and other behaviors based on the purpose of the controller.
But still, I don't get the idea. Can someone explain what is the purpose of this attribute with the real-life example?
ASP.NET Web API is a framework that helps you to build services by making it easy to reach a wide range of clients including browsers, mobiles, tablets, etc. With the help of ASP.NET, you can use the same framework and same patterns for creating web pages and services both.
Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder.
ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the . NET Framework. 132.0M. Microsoft.AspNet.WebApi.Owin.
This is well-explained in the docs: Annotation with ApiController attribute, which explains that adding the [ApiController]
attribute to a controller does the following:
Automatic HTTP 400 responses
Adds an action filter that returns a 400 response if ModelState.IsValid
is false
.
Binding source parameter inference
Changes model-binding conventions. For example, [FromBody]
is inferred for complex-type parameters.
Multipart/form-data request inference
Infers a Content-Type of multipart/form-data
for parameters marked with [FromForm]
.
Attribute routing requirement
Mandates that all actions must be attribute-routed.
You can see how this is actually done in the source:
foreach (var actionModel in controllerModel.Actions)
{
if (!isApiController && !actionModel.Attributes.OfType<IApiBehaviorMetadata>().Any())
{
continue;
}
EnsureActionIsAttributeRouted(controllerHasSelectorModel, actionModel);
AddInvalidModelStateFilter(actionModel);
InferParameterBindingSources(actionModel);
InferParameterModelPrefixes(actionModel);
AddMultipartFormDataConsumesAttribute(actionModel);
}
If you're not interested in any of the features described above, you can omit the attribute. It's also possible to suppress individual features by configuring the ApiBehaviorOptions
class.
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