webapi

That’s using asp.net core and using c# to create Restful services, that’s webapi, if you’re going to use webapi controllers

Controllers in WebAPI are classes derived from ControllerBase,

ControllerBase class

Do not create Web API controllers by deriving from the Controller class. Controller is derived from ControllerBase and adds support for views, so it is used to process Web pages, not Web API requests. There is one exception to this rule: if you intend to use the same Controller for your view and Web API, derive the Controller from the Controller.

The ControllerBase class provides a number of properties and methods for handling HTTP requests.

For example, ControllerBase. CreatedAtAction return 201 status code:

Here are some more examples of the methods ControllerBase provides.

methods instructions
BadRequest Returns the 400 status code.
NotFound Returns the 404 status code.
PhysicalFile Return the file.
TryUpdateModelAsync callModel binding.
TryValidateModel callModel validation.

features

The microsoft.aspnetcore.mvc namespace provides properties that can be used to configure the behavior and operation methods of the Web API controller. The following example uses properties to specify supported HTTP action actions and all known HTTP status codes that can be returned:

[HttpPost][ProducesResponseType(StatusCodes.Status201Created)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
public ActionResult<Pet> Create(Pet pet)
{
pet.Id = _petsInMemoryStore.Any() ? 
_petsInMemoryStore.Max(p => p.Id) + 1 : 1;
_petsInMemoryStore.Add(pet);
return CreatedAtAction(nameof(GetById), new { id = pet.Id }, pet);
}
Copy the code
features instructions
[[Route\]] Specifies the URL pattern for the controller or operation.
[[Bind\]] Specify the prefix and attributes to include for model binding.
[[HttpGet\]] Identifies operations that support HTTP GET operation predicates.
[[Consumes\]] Specifies the type of data that an operation accepts.
[[Produces\]] Specifies the type of data returned by an operation.

ApiController features

Properties on a specific controller

The [[ApiController\]] property can be applied to a controller class to enable the following API-specific fixed behavior:

Compatibility version 2.2 or higher is required to use the Problem Details for Error Status Codes feature. You must have compatibility version 2.1 or higher to use other features.

Features on multiple controllers

One way to use this property on multiple controllers is to create a custom base controller class annotated with the [ApiController] property. The following example shows a custom base class and controllers derived from it:

[ApiController]
public class MyControllerBase : ControllerBase{}Copy the code
[Produces(MediaTypeNames.Application.Json)]
[Route("[controller]")]
public class PetsController : MyControllerBase
Copy the code

On – assembly properties

If the compatibility version is set to 2.2 or higher, the [ApiController] property can be applied to an assembly. Annotating in this way applies web API behavior to all controllers in the assembly. The opt-out operation cannot be performed for a single controller. Apply assembly-level properties to namespace declarations on either side of the Startup class:

[assembly: ApiController]
namespace WebApiSample
{
    public class Startup{... }}Copy the code

Feature Routing requirements

The [ApiController] attribute makes attribute routing a requirement. Such as:

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
Copy the code

Cannot be accessed through traditional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in startup. Configure.

Automatic HTTP 400 response

The [ApiController] property causes model validation errors to automatically trigger HTTP 400 responses. Therefore, the following code is not required in the action method:

if(! ModelState.IsValid) {return BadRequest(ModelState);
}
Copy the code

ASP.NET Core MVC uses the ModelStateInvalidFilter action filter to perform the above checks.

Default BadRequest response

When using compatibility version 2.1, the default HTTP 400 response type is SerializableError. The following request body is an example of a serialization type:

JSON

{
  "": [
    "A non-empty request body is required."]}Copy the code

The default response type for HTTP 400 responses when using compatibility versions 2.2 or higher is ValidationProblemDetails. The following request body is an example of a serialization type:

JSON

{
  "type": "https://tools.ietf.org/html/rfc7231#section-6.5.1"."title": "One or more validation errors occurred."."status": 400."traceId": "|7fb5e16a-4c8f23bbfc974667."."errors": {
    "": [
      "A non-empty request body is required."]}}Copy the code

ValidationProblemDetails type:

  • Provide a computer-readable format to specify errors in Web API responses.
  • Complies with RFC 7807 specification.

Record automatic 400 responses

See how to automatically respond to 400 Model validation error logs (aspnet/ aspnetcore.docs #12157).

Disable automatic 400 response

If you want to disable automatic 400 behavior, please put SuppressModelStateInvalidFilter attribute set to true. Add the following code highlighted to Startup. The ConfigureServices:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
Copy the code

Bind source parameter reasoning

The binding source property defines where the value of the action parameter can be found. The following binding source features exist:

features The binding source
[[FromBody\]] Request body
[[FromForm\]] Request form data in the body
[[FromHeader\]] The request header
[[FromQuery\]] Request a query for string parameters
[[FromRoute\]] Routing data in the current request
[[FromServices\]] The request service inserted as an operation parameter

Without an [ApiController] attribute or a binding source attribute such as [FromQuery], ASP.NET Core runtime tries to use a complex object model binder. The complex object model binder pulls data from the value provider in a defined order.

In the following example, the [FromQuery] feature indicates that discontinuedOnly values are provided in the query string of the request URL:

[HttpGet]
public ActionResult<List<Product>> Get(
    [FromQuery] bool discontinuedOnly = false)
{
    List<Product> products = null;

    if (discontinuedOnly)
    {
        products = _productsInMemoryStore.Where(p => p.IsDiscontinued).ToList();
    }
    else
    {
        products = _productsInMemoryStore;
    }

    return products;
}
Copy the code

The [ApiController] property applies inference rules to the default data source for action parameters. These rules eliminate the need to manually identify binding sources by applying properties to action parameters. Binding source inference rules behave as follows:

  • [FromBody]Make inferences for complex type parameters.[FromBody]Does not apply to any complex built-in type with special meaning, such asIFormCollection 和 CancellationToken. The binding source inference code ignores these special types.
  • [FromForm]forIFormFile 和 IFormFileCollectionType operation parameters to be inferred. This feature does not infer for any simple or user-defined type.
  • [FromRoute]Infer any operation parameter names that match the parameters in the routing template. When multiple routes match an operation parameter, any route value is considered[FromRoute].
  • [FromQuery]Extrapolate for any other operational parameters.

FromBody reasoning

For simple types (such as String or int), [FromBody] cannot be inferred. Therefore, if this functionality is needed, the [FromBody] attribute should be used for simple types.

An exception is thrown when an operation has more than one parameter bound from the request body. For example, all of the following action method signatures cause exceptions:

  • [FromBody] makes inferences about both because they are complex types.

    [HttpPost]
    public IActionResult Action1(Product product, Order order)
    Copy the code
  • [FromBody] attributing to one and inferring to the other because it’s a complex type.

    [HttpPost]
    public IActionResult Action2(Product product, [FromBody] Order order)
    Copy the code
  • [FromBody] ascribe to both.

    [HttpPost]
    public IActionResult Action3([FromBody] Product product, [FromBody] Order o
    Copy the code

Forbidden inference rule

If you want to disable the binding source reasoning, please put SuppressInferBindingSourcesForParameters set to true. In the Startup. ConfigureServices to add the following code:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
Copy the code

Multipart/form-data request reasoning

When the [FromForm\] attribute is used to annotate operation parameters, the [ApiController] attribute applies inference rules. The multipart/form-data request content type is inferred.

To disable the default behavior, in the Startup will SuppressConsumesConstraintForFormFileParameters ConfigureServices attribute is set to true:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
Copy the code

Problem details for the error status code

Disable the ProblemDetails response

When the SuppressMapClientErrors property is set to True, the automatic creation of the ProblemDetails for the error status code is disabled. In the Startup. ConfigureServices to add the following code:

services.AddControllers()
    .ConfigureApiBehaviorOptions(options =>
    {
        options.SuppressConsumesConstraintForFormFileParameters = true;
        options.SuppressInferBindingSourcesForParameters = true;
        options.SuppressModelStateInvalidFilter = true;
        options.SuppressMapClientErrors = true;
        options.ClientErrorMapping[404].Link =
            "https://httpstatuses.com/404";
    });
Copy the code

Use [Consumes] attribute to define the content types for the requests that are supported

By default, the operation supports all available request content types. For example, if the application is configured to support both JSON and XML input formatters, the operation supports multiple content types, including Application/JSON and Application/XML.

Using the [Consumes] attribute, the operation limits the types of content for requests that are supported. Applies the [Consumes] property to an operation or controller and specifies one or more content types:

[HttpPost]
[Consumes("application/xml")]
public IActionResult CreateProduct(Product product)
Copy the code

In the above code, the CreateProduct operation specifies the content type Application/XML. Requests routed to this operation must specify the Application/XML content-Type header. If the request does not specify an application/ XML content-type header, a media Type response not supported by 415 is generated.

Using the [Consumes] property, an operation can apply type constraints to affect the selection of an incoming request based on the content type. Take a look at the following example:

[ApiController]
[Route("api/[controller]")]
public class ConsumesController : ControllerBase{[HttpPost]
    [Consumes("application/json")]
    public IActionResult PostJson(IEnumerable<int> values) =>
        Ok(new { Consumes = "application/json", Values = values });

    [HttpPost]
    [Consumes("application/x-www-form-urlencoded")]
    public IActionResult PostForm([FromForm] IEnumerable<int> values) =>
        Ok(new { Consumes = "application/x-www-form-urlencoded", Values = values });
}
Copy the code

In the code above, ConsumesController configured to process request sent to the https://localhost:5001/api/Consumes URL. Both operations on the controller (PostJson and PostForm) use the same URL to process POST requests. If the [Consumes] property does not apply type constraints, it throws an ambiguous match exception.

The [Consumes] property applies to two operations. The PostJson operation handles content-type hair requests using application/ JSON. The PostForm operation handles requests for Content-type hair sent using Application/X-www-form-urlencoded.