ASP.NET Core Web API Getting Started Notes
TLDR
ControllerBaseis suitable for pure Web API development; inherit fromControllerif View support or Filter events are required.[ApiController]provides automated behaviors such as attribute routing, automatic HTTP 400 responses, and parameter binding inference.- It is recommended to use
ActionResult<T>as the Action return type to balance data return and status code control. - For routing configuration, it is recommended to use the
[Route]attribute and explicitly specify verbs like[HttpGet],[HttpPost], etc. - When integrating Swagger, ensure every Action has an HTTP attribute; otherwise, the UI display may be abnormal.
- You can use
IOperationFilterto add custom fields (such as Tokens) in Swagger. - Enabling XML documentation comments can significantly improve the quality of Swagger documentation; you need to set
GenerateDocumentationFilein the.csprojfile.
Project Creation and Basic Configuration
When creating a Web API project in Visual Studio, consider the following:
- Enable OpenAPI support: Checking this will automatically install
Swashbuckle.AspNetCoreand configure Swagger. - Top-level statements: A C# 9.0 feature that simplifies the
Program.csstructure by removing the traditionalProgramclass andMainmethod. - Use controllers: If unchecked, "Minimal APIs" will be created, which is suitable for lightweight services.
Controller and ApiController Explanation
Differences between ControllerBase and Controller
When to encounter this: When you need to decide the base class for your Controller.
ControllerBase: The default base class for Web API, which does not include View-related functionality.Controller: Inherits fromControllerBaseand provides additional View support and Filter events likeOnActionExecuting. If you need to support both Views and APIs, it is recommended to inherit from this class.
ApiController Behavior
When to encounter this: When you want to simplify API validation and parameter binding logic. After marking with [ApiController], the system automatically enables the following features:
- Attribute routing requirement.
- Automatic HTTP 400 responses (automatic
ModelStatecheck). - Binding source parameter inference (e.g.,
[FromBody],[FromQuery], etc.). - Multipart/form-data request inference.
- Problem details for error status codes.
If you need to disable some behaviors, you can adjust them via ConfigureApiBehaviorOptions in AddControllers() within Program.cs.
Routing and Parameter Binding
Attribute Routing
When to encounter this: When you need to define RESTful style or custom API paths. ASP.NET Core uses the [Route] attribute for routing configuration. The priority from high to low is: Action > Controller > Base Class.
TIP
- After setting
[ApiController], conventional routing (such as routes defined byUseEndpoints) will be disabled. - Use square brackets
[]for route parameters (e.g.,[controller]), rather than the curly braces{}used in conventional routing.
Parameter Binding Inference
When to encounter this: When you need to explicitly specify the parameter source. The system automatically infers the source based on the type:
[FromBody]: Complex types.[FromForm]:IFormFileorIFormFileCollection.[FromRoute]: Parameters matching the route template.[FromQuery]: Other parameters.
Return Type Recommendations
When to encounter this: When you need to standardize the return format of your API. It is recommended to prioritize ActionResult<T>, as it allows developers to return both data and HTTP status codes, and it correctly displays the return type in Swagger documentation.
[HttpGet("{id}")]
public ActionResult<string> GetById(int? id) {
if (!id.HasValue) {
return BadRequest("Invalid id");
}
return $"GET method with id {id}";
}Swagger Integration and Best Practices
Ensuring Swagger Works Correctly
When to encounter this: When your API cannot be correctly displayed or tested in the Swagger UI. Note: Even if an HTTP attribute is not explicitly set, the API defaults to a GET request. However, to ensure Swagger can correctly parse and display descriptions, be sure to explicitly mark each Action with an attribute like [HttpGet] or [HttpPost], and avoid designing public methods that are not intended as Actions.
Integrating XML Comments
When to encounter this: When you need your API documentation to include detailed parameter descriptions and examples.
- Add the following configuration to your
.csproj:
<PropertyGroup>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);1591</NoWarn>
</PropertyGroup>- Add the XML path configuration in
AddSwaggerGenwithinProgram.cs:
builder.Services.AddSwaggerGen(opt => {
string xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
opt.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename));
});Extending Swagger Functionality
When to encounter this: When you need to add global parameters (such as Tokens). You can implement the IOperationFilter interface and register it in AddSwaggerGen to add custom input fields to all API interfaces.
Change Log
- 2023-08-04 Initial document creation.
