ASP.NET Core Notes
Json Field Rename
When formating model class data to json string, the default json field name is the model class property name(with some possible case change). If a customized field name is required, we can add attribute to properties to indicate ASP.NET to do it:
- Add NewtonsoftJson support in ASP.NET project. Install the package
Microsoft.AspNetCore.Mvc.NewtonsoftJson
. Then in main, we can add support bybuilder.Services.AddControllers().AddNewtonsoftJson()
. - Annotate model class properties with
[JsonProperty(PropertyName = "haha")]
, where we can replace our customized name. After these steps, json formatter will take our customized names into consideration when serializing model data.
Return Common Code From Controller
The action function’s return type may be ActionResult
or async Task<ActionResult>
. And Ok()
, StatusCode(code)
may be returned to specify the HTTP response code.
Model Binding
When Web API calls a method on a controller, its parameters must be set values, a process called model binding (or parameter binding). Here are basic rules:
- If the parameter is a “simple” type, it tries to parse it from url’s query string.
- If the parameter is a “complex” type, it tries to parse it from body, such as json or xml. A “media-type formatter” is used to parse it.
[FromQuery] and [FromBody] Attributes
These attributes can be used to decorate parameters to force them to be parsed from query string and body data. [FromBody] can only be applied once in parameters.
Bind Json Array
If we want to bind json array to parameters, we can use [FromBody]
, and List<SomeType>
, to parse top json array in body.
Bind Url Path to Parameters
If we want to parse a section in url to controller’s parameter, RouteAttribute
can be used to achieve this:
[Route("api/{controller}/{action}/{myid}")]
public async Task<IActionResult> GetSth(string myid)
{
...
}
RouteAttribute Concatenation
If we have a controller with attribute [Route("api/{controller}/{action}")]
, and we make an action method [Route("{myid}")]
, the full path to this action is [Route("api/{controller}/{action}/{myid}")]
.
[BindProperty] and [BindProperties]
[BindProperty]
can be applied to public property of controller or PageModel
class to cause model binding to target that property.
[BindProperties]
can be applied to controller class to request model binding to target all public properties.