This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Note
Access to this page requires authorization. You can trysigning in orchanging directories.
Access to this page requires authorization. You can trychanging directories.
ASP.NET Core supports creating web APIs using controllers or using minimal APIs.Controllers in a web API are classes that derive fromControllerBase. Controllers are activated and disposed on a per request basis.
This article shows how to use controllers for handling web API requests. For information on creating web APIs without controllers, seeTutorial: Create a minimal API with ASP.NET Core.
A controller-based web API consists of one or more controller classes that derive fromControllerBase. The web API project template provides a starter controller:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Web API controllers should typically derive fromControllerBase rather fromController.Controller
derives fromControllerBase and adds support for views, so it's for handling web pages, not web API requests. If the same controller must support views and web APIs, derive fromController
.
TheControllerBase
class provides many properties and methods that are useful for handling HTTP requests. For example,CreatedAtAction returns a 201 status code:
[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);}
The following table contains examples of methods inControllerBase
.
Method | Notes |
---|---|
BadRequest | Returns 400 status code. |
NotFound | Returns 404 status code. |
PhysicalFile | Returns a file. |
TryUpdateModelAsync | Invokesmodel binding. |
TryValidateModel | Invokesmodel validation. |
For a list of all available methods and properties, seeControllerBase.
TheMicrosoft.AspNetCore.Mvc namespace provides attributes that can be used to configure the behavior of web API controllers and action methods. The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could 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);}
Here are some more examples of attributes that are available.
Attribute | Notes |
---|---|
[Route] | Specifies URL pattern for a controller or action. |
[Bind] | Specifies prefix and properties to include for model binding. |
[HttpGet] | Identifies an action that supports the HTTP GET action verb. |
[Consumes] | Specifies data types that an action accepts. |
[Produces] | Specifies data types that an action returns. |
For a list that includes the available attributes, see theMicrosoft.AspNetCore.Mvc namespace.
The[ApiController]
attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
The[ApiController]
attribute can be applied to specific controllers, as in the following example from the project template:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the[ApiController]
attribute. The following example shows a custom base class and a controller that derives from it:
[ApiController]public class MyControllerBase : ControllerBase{}
[Produces(MediaTypeNames.Application.Json)][Route("[controller]")]public class PetsController : MyControllerBase
The[ApiController]
attribute can be applied to an assembly. When the[ApiController]
attribute is applied to an assembly, all controllers in the assembly have the[ApiController]
attribute applied. There's no way to opt out for individual controllers. Apply the assembly-level attribute to theProgram.cs
file:
using Microsoft.AspNetCore.Mvc;[assembly: ApiController]var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
The[ApiController]
attribute makes attribute routing a requirement. For example:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Actions are inaccessible viaconventional routes defined byUseEndpoints
,UseMvc, orUseMvcWithDefaultRoute.
The[ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:
if (!ModelState.IsValid){ return BadRequest(ModelState);}
ASP.NET Core MVC uses theModelStateInvalidFilter action filter to do the preceding check.
The default response type for an HTTP 400 response isValidationProblemDetails. The following response body is an example of the serialized type:
{ "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." ] }}
TheValidationProblemDetails
type:
To make automatic and custom responses consistent, call theValidationProblem method instead ofBadRequest.ValidationProblem
returns aValidationProblemDetails object as well as the automatic response.
To log automatic 400 responses, set theInvalidModelStateResponseFactory delegate property to perform custom processing. By default,InvalidModelStateResponseFactory
usesProblemDetailsFactory to create an instance ofValidationProblemDetails.
The following example shows how to retrieve an instance ofILogger<TCategoryName> to log information about an automatic 400 response:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { // To preserve the default behavior, capture the original delegate to call later. var builtInFactory = options.InvalidModelStateResponseFactory; options.InvalidModelStateResponseFactory = context => { var logger = context.HttpContext.RequestServices .GetRequiredService<ILogger<Program>>(); // Perform logging here. // ... // Invoke the default behavior, which produces a ValidationProblemDetails // response. // To produce a custom response, return a different implementation of // IActionResult instead. return builtInFactory(context); }; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
To disable the automatic 400 behavior, set theSuppressModelStateInvalidFilter property totrue
. Add the following highlighted code:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
A binding source attribute defines the location at which an action parameter's value is found. The following binding source attributes exist:
Attribute | Binding source |
---|---|
[FromBody] | Request body |
[FromForm] | Form data in the request body |
[FromHeader] | Request header |
[FromQuery] | Request query string parameter |
[FromRoute] | Route data from the current request |
[FromServices] | The request service injected as an action parameter |
[AsParameters] | Method parameters |
Warning
Don't use[FromRoute]
when values might contain%2f
(that is/
).%2f
won't be unescaped to/
. Use[FromQuery]
if the value might contain%2f
.
Without the[ApiController]
attribute or binding source attributes like[FromQuery]
, the ASP.NET Core runtime attempts to use the complex object model binder. The complex object model binder pulls data from value providers in a defined order.
In the following example, the[FromQuery]
attribute indicates that thediscontinuedOnly
parameter value is provided in the request URL's query string:
[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;}
The[ApiController]
attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters. The binding source inference rules behave as follows:
[FromServices]
is inferred for complex type parameters registered in the DI Container.[FromBody]
is inferred for complex type parameters not registered in the DI Container. An exception to the[FromBody]
inference rule is any complex, built-in type with a special meaning, such asIFormCollection andCancellationToken. The binding source inference code ignores those special types.[FromForm]
is inferred for action parameters of typeIFormFile andIFormFileCollection. It's not inferred for any simple or user-defined types.[FromRoute]
is inferred for any action parameter name matching a parameter in the route template. When more than one route matches an action parameter, any route value is considered[FromRoute]
.[FromQuery]
is inferred for any other action parameters.[FromBody]
isn't inferred for simple types such asstring
orint
. Therefore, the[FromBody]
attribute should be used for simple types when that functionality is needed.
When an action has more than one parameter bound from the request body, an exception is thrown. For example, all of the following action method signatures cause an exception:
[FromBody]
inferred on both because they're complex types.
[HttpPost]public IActionResult Action1(Product product, Order order)
[FromBody]
attribute on one, inferred on the other because it's a complex type.
[HttpPost]public IActionResult Action2(Product product, [FromBody] Order order)
[FromBody]
attribute on both.
[HttpPost]public IActionResult Action3([FromBody] Product product, [FromBody] Order order)
Parameter binding binds parameters throughdependency injection when the type is configured as a service. This means it's not required to explicitly apply the[FromServices]
attribute to a parameter. In the following code, both actions return the time:
[Route("[controller]")][ApiController]public class MyController : ControllerBase{ public ActionResult GetWithAttribute([FromServices] IDateTime dateTime) => Ok(dateTime.Now); [Route("noAttribute")] public ActionResult Get(IDateTime dateTime) => Ok(dateTime.Now);}
In rare cases, automatic DI can break apps that have a type in DI that is also accepted in an API controller's action methods. It's not common to have a type in DI and as an argument in an API controller action.
To disable[FromServices]
inference for a single action parameter, apply the desired binding source attribute to the parameter. For example, apply the[FromBody]
attribute to an action parameter that should be bound from the body of the request.
To disable[FromServices]
inference globally, setDisableImplicitFromServicesParameters totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();builder.Services.AddSingleton<IDateTime, SystemDateTime>();builder.Services.Configure<ApiBehaviorOptions>(options =>{ options.DisableImplicitFromServicesParameters = true;});var app = builder.Build();app.MapControllers();app.Run();
Types are checked at app startup withIServiceProviderIsService to determine if an argument in an API controller action comes from DI or from the other sources.
The mechanism to infer binding source of API Controller action parameters uses the following rules:
BindingInfo.BindingSource
is never overwritten.BindingSource.Services
.BindingSource.Body
.BindingSource.Path
.BindingSource.Query
.To disable binding source inference, setSuppressInferBindingSourcesForParameters totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; options.DisableImplicitFromServicesParameters = true; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
The[ApiController]
attribute applies an inference rule for action parameters of typeIFormFile andIFormFileCollection. Themultipart/form-data
request content type is inferred for these types.
To disable the default behavior, set theSuppressConsumesConstraintForFormFileParameters property totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
MVC transforms an error result (a result with status code 400 or higher) to a result withProblemDetails. TheProblemDetails
type is based on theRFC 7807 specification for providing machine-readable error details in an HTTP response.
Consider the following code in a controller action:
if (pet == null){ return NotFound();}
TheNotFound
method produces an HTTP 404 status code with aProblemDetails
body. For example:
{ type: "https://tools.ietf.org/html/rfc7231#section-6.5.4", title: "Not Found", status: 404, traceId: "0HLHLV31KRN83:00000001"}
The automatic creation of aProblemDetails
for error status codes is disabled when theSuppressMapClientErrors property is set totrue
. Add the following code:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
By default, an action supports all available request content types. For example, if an app is configured to support both JSON and XMLinput formatters, an action supports multiple content types, includingapplication/json
andapplication/xml
.
The[Consumes] attribute allows an action to limit the supported request content types. Apply the[Consumes]
attribute to an action or controller, specifying one or more content types:
[HttpPost][Consumes("application/xml")]public IActionResult CreateProduct(Product product)
In the preceding code, theCreateProduct
action specifies the content typeapplication/xml
. Requests routed to this action must specify aContent-Type
header ofapplication/xml
. Requests that don't specify aContent-Type
header ofapplication/xml
result in a415 Unsupported Media Type response.
The[Consumes]
attribute also allows an action to influence its selection based on an incoming request's content type by applying a type constraint. Consider 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 });}
In the preceding code,ConsumesController
is configured to handle requests sent to thehttps://localhost:5001/api/Consumes
URL. Both of the controller's actions,PostJson
andPostForm
, handle POST requests with the same URL. Without the[Consumes]
attribute applying a type constraint, an ambiguous match exception is thrown.
The[Consumes]
attribute is applied to both actions. ThePostJson
action handles requests sent with aContent-Type
header ofapplication/json
. ThePostForm
action handles requests sent with aContent-Type
header ofapplication/x-www-form-urlencoded
.
ASP.NET Core supports creating web APIs using controllers or using minimal APIs.Controllers in a web API are classes that derive fromControllerBase. This article shows how to use controllers for handling web API requests. For information on creating web APIs without controllers, seeTutorial: Create a minimal API with ASP.NET Core.
A controller-based web API consists of one or more controller classes that derive fromControllerBase. The web API project template provides a starter controller:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Web API controllers should typically derive fromControllerBase rather fromController.Controller
derives fromControllerBase and adds support for views, so it's for handling web pages, not web API requests. If the same controller must support views and web APIs, derive fromController
.
TheControllerBase
class provides many properties and methods that are useful for handling HTTP requests. For example,CreatedAtAction returns a 201 status code:
[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);}
The following table contains examples of methods inControllerBase
.
Method | Notes |
---|---|
BadRequest | Returns 400 status code. |
NotFound | Returns 404 status code. |
PhysicalFile | Returns a file. |
TryUpdateModelAsync | Invokesmodel binding. |
TryValidateModel | Invokesmodel validation. |
For a list of all available methods and properties, seeControllerBase.
TheMicrosoft.AspNetCore.Mvc namespace provides attributes that can be used to configure the behavior of web API controllers and action methods. The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could 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);}
Here are some more examples of attributes that are available.
Attribute | Notes |
---|---|
[Route] | Specifies URL pattern for a controller or action. |
[Bind] | Specifies prefix and properties to include for model binding. |
[HttpGet] | Identifies an action that supports the HTTP GET action verb. |
[Consumes] | Specifies data types that an action accepts. |
[Produces] | Specifies data types that an action returns. |
For a list that includes the available attributes, see theMicrosoft.AspNetCore.Mvc namespace.
The[ApiController]
attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
The[ApiController]
attribute can be applied to specific controllers, as in the following example from the project template:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the[ApiController]
attribute. The following example shows a custom base class and a controller that derives from it:
[ApiController]public class MyControllerBase : ControllerBase{}
[Produces(MediaTypeNames.Application.Json)][Route("[controller]")]public class PetsController : MyControllerBase
The[ApiController]
attribute can be applied to an assembly. When the[ApiController]
attribute is applied to an assembly, all controllers in the assembly have the[ApiController]
attribute applied. There's no way to opt out for individual controllers. Apply the assembly-level attribute to theProgram.cs
file:
using Microsoft.AspNetCore.Mvc;[assembly: ApiController]var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers();var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
The[ApiController]
attribute makes attribute routing a requirement. For example:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Actions are inaccessible viaconventional routes defined byUseEndpoints
,UseMvc, orUseMvcWithDefaultRoute.
The[ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:
if (!ModelState.IsValid){ return BadRequest(ModelState);}
ASP.NET Core MVC uses theModelStateInvalidFilter action filter to do the preceding check.
The following response body is an example of the serialized type:
{ "": [ "A non-empty request body is required." ]}
The default response type for an HTTP 400 response isValidationProblemDetails. The following response body is an example of the serialized type:
{ "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." ] }}
TheValidationProblemDetails
type:
To make automatic and custom responses consistent, call theValidationProblem method instead ofBadRequest.ValidationProblem
returns aValidationProblemDetails object as well as the automatic response.
To log automatic 400 responses, set theInvalidModelStateResponseFactory delegate property to perform custom processing. By default,InvalidModelStateResponseFactory
usesProblemDetailsFactory to create an instance ofValidationProblemDetails.
The following example shows how to retrieve an instance ofILogger<TCategoryName> to log information about an automatic 400 response:
var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { // To preserve the default behavior, capture the original delegate to call later. var builtInFactory = options.InvalidModelStateResponseFactory; options.InvalidModelStateResponseFactory = context => { var logger = context.HttpContext.RequestServices .GetRequiredService<ILogger<Program>>(); // Perform logging here. // ... // Invoke the default behavior, which produces a ValidationProblemDetails // response. // To produce a custom response, return a different implementation of // IActionResult instead. return builtInFactory(context); }; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
To disable the automatic 400 behavior, set theSuppressModelStateInvalidFilter property totrue
. Add the following highlighted code:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
A binding source attribute defines the location at which an action parameter's value is found. The following binding source attributes exist:
Attribute | Binding source |
---|---|
[FromBody] | Request body |
[FromForm] | Form data in the request body |
[FromHeader] | Request header |
[FromQuery] | Request query string parameter |
[FromRoute] | Route data from the current request |
[FromServices] | The request service injected as an action parameter |
Warning
Don't use[FromRoute]
when values might contain%2f
(that is/
).%2f
won't be unescaped to/
. Use[FromQuery]
if the value might contain%2f
.
Without the[ApiController]
attribute or binding source attributes like[FromQuery]
, the ASP.NET Core runtime attempts to use the complex object model binder. The complex object model binder pulls data from value providers in a defined order.
In the following example, the[FromQuery]
attribute indicates that thediscontinuedOnly
parameter value is provided in the request URL's query string:
[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;}
The[ApiController]
attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters. The binding source inference rules behave as follows:
[FromBody]
is inferred for complex type parameters not registered in the DI Container. An exception to the[FromBody]
inference rule is any complex, built-in type with a special meaning, such asIFormCollection andCancellationToken. The binding source inference code ignores those special types.[FromForm]
is inferred for action parameters of typeIFormFile andIFormFileCollection. It's not inferred for any simple or user-defined types.[FromRoute]
is inferred for any action parameter name matching a parameter in the route template. When more than one route matches an action parameter, any route value is considered[FromRoute]
.[FromQuery]
is inferred for any other action parameters.[FromBody]
isn't inferred for simple types such asstring
orint
. Therefore, the[FromBody]
attribute should be used for simple types when that functionality is needed.
When an action has more than one parameter bound from the request body, an exception is thrown. For example, all of the following action method signatures cause an exception:
[FromBody]
inferred on both because they're complex types.
[HttpPost]public IActionResult Action1(Product product, Order order)
[FromBody]
attribute on one, inferred on the other because it's a complex type.
[HttpPost]public IActionResult Action2(Product product, [FromBody] Order order)
[FromBody]
attribute on both.
[HttpPost]public IActionResult Action3([FromBody] Product product, [FromBody] Order order)
To disable binding source inference, setSuppressInferBindingSourcesForParameters totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
The[ApiController]
attribute applies an inference rule for action parameters of typeIFormFile andIFormFileCollection. Themultipart/form-data
request content type is inferred for these types.
To disable the default behavior, set theSuppressConsumesConstraintForFormFileParameters property totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
MVC transforms an error result (a result with status code 400 or higher) to a result withProblemDetails. TheProblemDetails
type is based on theRFC 7807 specification for providing machine-readable error details in an HTTP response.
Consider the following code in a controller action:
if (pet == null){ return NotFound();}
TheNotFound
method produces an HTTP 404 status code with aProblemDetails
body. For example:
{ type: "https://tools.ietf.org/html/rfc7231#section-6.5.4", title: "Not Found", status: 404, traceId: "0HLHLV31KRN83:00000001"}
The automatic creation of aProblemDetails
for error status codes is disabled when theSuppressMapClientErrors property is set totrue
:
using Microsoft.AspNetCore.Mvc;var builder = WebApplication.CreateBuilder(args);builder.Services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; });var app = builder.Build();app.UseHttpsRedirection();app.UseAuthorization();app.MapControllers();app.Run();
By default, an action supports all available request content types. For example, if an app is configured to support both JSON and XMLinput formatters, an action supports multiple content types, includingapplication/json
andapplication/xml
.
The[Consumes] attribute allows an action to limit the supported request content types. Apply the[Consumes]
attribute to an action or controller, specifying one or more content types:
[HttpPost][Consumes("application/xml")]public IActionResult CreateProduct(Product product)
In the preceding code, theCreateProduct
action specifies the content typeapplication/xml
. Requests routed to this action must specify aContent-Type
header ofapplication/xml
. Requests that don't specify aContent-Type
header ofapplication/xml
result in a415 Unsupported Media Type response.
The[Consumes]
attribute also allows an action to influence its selection based on an incoming request's content type by applying a type constraint. Consider 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 });}
In the preceding code,ConsumesController
is configured to handle requests sent to thehttps://localhost:5001/api/Consumes
URL. Both of the controller's actions,PostJson
andPostForm
, handle POST requests with the same URL. Without the[Consumes]
attribute applying a type constraint, an ambiguous match exception is thrown.
The[Consumes]
attribute is applied to both actions. ThePostJson
action handles requests sent with aContent-Type
header ofapplication/json
. ThePostForm
action handles requests sent with aContent-Type
header ofapplication/x-www-form-urlencoded
.
ASP.NET Core supports creating RESTful services, also known as web APIs, using C#. To handle requests, a web API uses controllers.Controllers in a web API are classes that derive fromControllerBase
. This article shows how to use controllers for handling web API requests.
View or download sample code. (How to download).
A web API consists of one or more controller classes that derive fromControllerBase. The web API project template provides a starter controller:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Don't create a web API controller by deriving from theController class.Controller
derives fromControllerBase
and adds support for views, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and web APIs, derive it fromController
.
TheControllerBase
class provides many properties and methods that are useful for handling HTTP requests. For example,ControllerBase.CreatedAtAction
returns a 201 status code:
[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);}
Here are some more examples of methods thatControllerBase
provides.
Method | Notes |
---|---|
BadRequest | Returns 400 status code. |
NotFound | Returns 404 status code. |
PhysicalFile | Returns a file. |
TryUpdateModelAsync | Invokesmodel binding. |
TryValidateModel | Invokesmodel validation. |
For a list of all available methods and properties, seeControllerBase.
TheMicrosoft.AspNetCore.Mvc namespace provides attributes that can be used to configure the behavior of web API controllers and action methods. The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could 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);}
Here are some more examples of attributes that are available.
Attribute | Notes |
---|---|
[Route] | Specifies URL pattern for a controller or action. |
[Bind] | Specifies prefix and properties to include for model binding. |
[HttpGet] | Identifies an action that supports the HTTP GET action verb. |
[Consumes] | Specifies data types that an action accepts. |
[Produces] | Specifies data types that an action returns. |
For a list that includes the available attributes, see theMicrosoft.AspNetCore.Mvc namespace.
The[ApiController]
attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
The[ApiController]
attribute can be applied to specific controllers, as in the following example from the project template:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the[ApiController]
attribute. The following example shows a custom base class and a controller that derives from it:
[ApiController]public class MyControllerBase : ControllerBase{}
[Produces(MediaTypeNames.Application.Json)][Route("[controller]")]public class PetsController : MyControllerBase
The[ApiController]
attribute can be applied to an assembly. Annotation in this manner applies web API behavior to all controllers in the assembly. There's no way to opt out for individual controllers. Apply the assembly-level attribute to the namespace declaration surrounding theStartup
class:
[assembly: ApiController]namespace WebApiSample{ public class Startup { ... }}
The[ApiController]
attribute makes attribute routing a requirement. For example:
[ApiController][Route("[controller]")]public class WeatherForecastController : ControllerBase
Actions are inaccessible viaconventional routes defined byUseEndpoints
,UseMvc, orUseMvcWithDefaultRoute inStartup.Configure
.
The[ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:
if (!ModelState.IsValid){ return BadRequest(ModelState);}
ASP.NET Core MVC uses theModelStateInvalidFilter action filter to do the preceding check.
The following request body is an example of the serialized type:
{ "": [ "A non-empty request body is required." ]}
The default response type for an HTTP 400 response isValidationProblemDetails. The following request body is an example of the serialized type:
{ "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." ] }}
TheValidationProblemDetails
type:
To make automatic and custom responses consistent, call theValidationProblem method instead ofBadRequest.ValidationProblem
returns aValidationProblemDetails object as well as the automatic response.
To log automatic 400 responses, set theInvalidModelStateResponseFactory delegate property to perform custom processing inStartup.ConfigureServices
. By default,InvalidModelStateResponseFactory
usesProblemDetailsFactory to create an instance ofValidationProblemDetails.
The following example shows how to retrieve an instance ofILogger<TCategoryName> to log information about an automatic 400 response:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { // To preserve the default behavior, capture the original delegate to call later. var builtInFactory = options.InvalidModelStateResponseFactory; options.InvalidModelStateResponseFactory = context => { var logger = context.HttpContext.RequestServices.GetRequiredService<ILogger<Startup>>(); // Perform logging here. // ... // Invoke the default behavior, which produces a ValidationProblemDetails response. // To produce a custom response, return a different implementation of IActionResult instead. return builtInFactory(context); }; });
To disable the automatic 400 behavior, set theSuppressModelStateInvalidFilter property totrue
. Add the following highlighted code inStartup.ConfigureServices
:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; options.DisableImplicitFromServicesParameters = true; });
A binding source attribute defines the location at which an action parameter's value is found. The following binding source attributes exist:
Attribute | Binding source |
---|---|
[FromBody] | Request body |
[FromForm] | Form data in the request body |
[FromHeader] | Request header |
[FromQuery] | Request query string parameter |
[FromRoute] | Route data from the current request |
[FromServices] | The request service injected as an action parameter |
Warning
Don't use[FromRoute]
when values might contain%2f
(that is/
).%2f
won't be unescaped to/
. Use[FromQuery]
if the value might contain%2f
.
Without the[ApiController]
attribute or binding source attributes like[FromQuery]
, the ASP.NET Core runtime attempts to use the complex object model binder. The complex object model binder pulls data from value providers in a defined order.
In the following example, the[FromQuery]
attribute indicates that thediscontinuedOnly
parameter value is provided in the request URL's query string:
[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;}
The[ApiController]
attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters. The binding source inference rules behave as follows:
[FromBody]
is inferred for complex type parameters. An exception to the[FromBody]
inference rule is any complex, built-in type with a special meaning, such asIFormCollection andCancellationToken. The binding source inference code ignores those special types.[FromForm]
is inferred for action parameters of typeIFormFile andIFormFileCollection. It's not inferred for any simple or user-defined types.[FromRoute]
is inferred for any action parameter name matching a parameter in the route template. When more than one route matches an action parameter, any route value is considered[FromRoute]
.[FromQuery]
is inferred for any other action parameters.[FromBody]
isn't inferred for simple types such asstring
orint
. Therefore, the[FromBody]
attribute should be used for simple types when that functionality is needed.
When an action has more than one parameter bound from the request body, an exception is thrown. For example, all of the following action method signatures cause an exception:
[FromBody]
inferred on both because they're complex types.
[HttpPost]public IActionResult Action1(Product product, Order order)
[FromBody]
attribute on one, inferred on the other because it's a complex type.
[HttpPost]public IActionResult Action2(Product product, [FromBody] Order order)
[FromBody]
attribute on both.
[HttpPost]public IActionResult Action3([FromBody] Product product, [FromBody] Order order)
To disable binding source inference, setSuppressInferBindingSourcesForParameters totrue
. Add the following code inStartup.ConfigureServices
:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; options.DisableImplicitFromServicesParameters = true; });
The[ApiController]
attribute applies an inference rule for action parameters of typeIFormFile andIFormFileCollection. Themultipart/form-data
request content type is inferred for these types.
To disable the default behavior, set theSuppressConsumesConstraintForFormFileParameters property totrue
inStartup.ConfigureServices
:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; options.DisableImplicitFromServicesParameters = true; });
MVC transforms an error result (a result with status code 400 or higher) to a result withProblemDetails. TheProblemDetails
type is based on theRFC 7807 specification for providing machine-readable error details in an HTTP response.
Consider the following code in a controller action:
if (pet == null){ return NotFound();}
TheNotFound
method produces an HTTP 404 status code with aProblemDetails
body. For example:
{ type: "https://tools.ietf.org/html/rfc7231#section-6.5.4", title: "Not Found", status: 404, traceId: "0HLHLV31KRN83:00000001"}
The automatic creation of aProblemDetails
for error status codes is disabled when theSuppressMapClientErrors property is set totrue
. Add the following code inStartup.ConfigureServices
:
services.AddControllers() .ConfigureApiBehaviorOptions(options => { options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true; options.SuppressMapClientErrors = true; options.ClientErrorMapping[StatusCodes.Status404NotFound].Link = "https://httpstatuses.com/404"; options.DisableImplicitFromServicesParameters = true; });
By default, an action supports all available request content types. For example, if an app is configured to support both JSON and XMLinput formatters, an action supports multiple content types, includingapplication/json
andapplication/xml
.
The[Consumes] attribute allows an action to limit the supported request content types. Apply the[Consumes]
attribute to an action or controller, specifying one or more content types:
[HttpPost][Consumes("application/xml")]public IActionResult CreateProduct(Product product)
In the preceding code, theCreateProduct
action specifies the content typeapplication/xml
. Requests routed to this action must specify aContent-Type
header ofapplication/xml
. Requests that don't specify aContent-Type
header ofapplication/xml
result in a415 Unsupported Media Type response.
The[Consumes]
attribute also allows an action to influence its selection based on an incoming request's content type by applying a type constraint. Consider 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 });}
In the preceding code,ConsumesController
is configured to handle requests sent to thehttps://localhost:5001/api/Consumes
URL. Both of the controller's actions,PostJson
andPostForm
, handle POST requests with the same URL. Without the[Consumes]
attribute applying a type constraint, an ambiguous match exception is thrown.
The[Consumes]
attribute is applied to both actions. ThePostJson
action handles requests sent with aContent-Type
header ofapplication/json
. ThePostForm
action handles requests sent with aContent-Type
header ofapplication/x-www-form-urlencoded
.
[Route("api/[controller]")][ApiController]public class ValuesController : ControllerBase
Don't create a web API controller by deriving from theController class.Controller
derives fromControllerBase
and adds support for views, so it's for handling web pages, not web API requests. There's an exception to this rule: if you plan to use the same controller for both views and web APIs, derive it fromController
.TheControllerBase
class provides many properties and methods that are useful for handling HTTP requests. For example,ControllerBase.CreatedAtAction
returns a 201 status code:
[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);}
Here are some more examples of methods thatControllerBase
provides:
Method | Notes |
---|---|
BadRequest | Returns 400 status code. |
NotFound | Returns 404 status code. |
PhysicalFile | Returns a file. |
TryUpdateModelAsync | Invokesmodel binding. |
TryValidateModel | Invokesmodel validation. |
For a list of all available methods and properties, seeControllerBase.
TheMicrosoft.AspNetCore.Mvc namespace provides attributes that can be used to configure the behavior of web API controllers and action methods. The following example uses attributes to specify the supported HTTP action verb and any known HTTP status codes that could 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);}
Here are some more examples of attributes that are available:
Attribute | Notes |
---|---|
[Route] | Specifies URL pattern for a controller or action. |
[Bind] | Specifies prefix and properties to include for model binding. |
[HttpGet] | Identifies an action that supports the HTTP GET action verb. |
[Consumes] | Specifies data types that an action accepts. |
[Produces] | Specifies data types that an action returns. |
For a list that includes the available attributes, see theMicrosoft.AspNetCore.Mvc namespace.
The[ApiController]
attribute can be applied to a controller class to enable the following opinionated, API-specific behaviors:
The[ApiController]
attribute can be applied to specific controllers, as in the following example from the project template:
[Route("api/[controller]")][ApiController]public class ValuesController : ControllerBase
One approach to using the attribute on more than one controller is to create a custom base controller class annotated with the[ApiController]
attribute. The following example shows a custom base class and a controller that derives from it:
[ApiController]public class MyControllerBase : ControllerBase{}
[Produces(MediaTypeNames.Application.Json)][Route("api/[controller]")]public class PetsController : MyControllerBase
Ifcompatibility version is set to 2.2 or later, the[ApiController]
attribute can be applied to an assembly. Annotation in this manner applies web API behavior to all controllers in the assembly. There's no way to opt out for individual controllers. Apply the assembly-level attribute to the namespace declaration surrounding theStartup
class:
[assembly: ApiController]namespace WebApiSample{ public class Startup { ... }}
The[ApiController]
attribute makes attribute routing a requirement. For example:
[Route("api/[controller]")][ApiController]public class ValuesController : ControllerBase
Actions are inaccessible viaconventional routes defined byUseMvc orUseMvcWithDefaultRoute inStartup.Configure
.
The[ApiController]
attribute makes model validation errors automatically trigger an HTTP 400 response. Consequently, the following code is unnecessary in an action method:
if (!ModelState.IsValid){ return BadRequest(ModelState);}
ASP.NET Core MVC uses theModelStateInvalidFilter action filter to do the preceding check.
With a compatibility version of 2.1, the default response type for an HTTP 400 response isSerializableError. The following request body is an example of the serialized type:
{ "": [ "A non-empty request body is required." ]}
With a compatibility version of 2.2 or later, the default response type for an HTTP 400 response isValidationProblemDetails. The following request body is an example of the serialized type:
{ "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." ] }}
TheValidationProblemDetails
type:
To make automatic and custom responses consistent, call theValidationProblem method instead ofBadRequest.ValidationProblem
returns aValidationProblemDetails object as well as the automatic response.
SeeHow to log automatic 400 responses on model validation errors (dotnet/AspNetCore.Docs#12157).
To disable the automatic 400 behavior, set theSuppressModelStateInvalidFilter property totrue
. Add the following highlighted code inStartup.ConfigureServices
:
services.Configure<ApiBehaviorOptions>(options =>{ options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true;});
A binding source attribute defines the location at which an action parameter's value is found. The following binding source attributes exist:
Attribute | Binding source |
---|---|
[FromBody] | Request body |
[FromForm] | Form data in the request body |
[FromHeader] | Request header |
[FromQuery] | Request query string parameter |
[FromRoute] | Route data from the current request |
[FromServices] | The request service injected as an action parameter |
Warning
Don't use[FromRoute]
when values might contain%2f
(that is/
).%2f
won't be unescaped to/
. Use[FromQuery]
if the value might contain%2f
.Without the[ApiController]
attribute or binding source attributes like[FromQuery]
, the ASP.NET Core runtime attempts to use the complex object model binder. The complex object model binder pulls data from value providers in a defined order.
In the following example, the[FromQuery]
attribute indicates that thediscontinuedOnly
parameter value is provided in the request URL's query string:
[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;}
The[ApiController]
attribute applies inference rules for the default data sources of action parameters. These rules save you from having to identify binding sources manually by applying attributes to the action parameters. The binding source inference rules behave as follows:
[FromBody]
is inferred for complex type parameters. An exception to the[FromBody]
inference rule is any complex, built-in type with a special meaning, such asIFormCollection andCancellationToken. The binding source inference code ignores those special types.[FromForm]
is inferred for action parameters of typeIFormFile andIFormFileCollection. It's not inferred for any simple or user-defined types.[FromRoute]
is inferred for any action parameter name matching a parameter in the route template. When more than one route matches an action parameter, any route value is considered[FromRoute]
.[FromQuery]
is inferred for any other action parameters.[FromBody]
isn't inferred for simple types such asstring
orint
. Therefore, the[FromBody]
attribute should be used for simple types when that functionality is needed.
When an action has more than one parameter bound from the request body, an exception is thrown. For example, all of the following action method signatures cause an exception:
[FromBody]
inferred on both because they're complex types.
[HttpPost]public IActionResult Action1(Product product, Order order)
[FromBody]
attribute on one, inferred on the other because it's a complex type.
[HttpPost]public IActionResult Action2(Product product, [FromBody] Order order)
[FromBody]
attribute on both.
[HttpPost]public IActionResult Action3([FromBody] Product product, [FromBody] Order order)
Note
In ASP.NET Core 2.1, collection type parameters such as lists and arrays are incorrectly inferred as[FromQuery]
. The[FromBody]
attribute should be used for these parameters if they are to be bound from the request body. This behavior is corrected in ASP.NET Core 2.2 or later, where collection type parameters are inferred to be bound from the body by default.
To disable binding source inference, setSuppressInferBindingSourcesForParameters totrue
. Add the following code inStartup.ConfigureServices
:
services.Configure<ApiBehaviorOptions>(options =>{ options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true;});
The[ApiController]
attribute applies an inference rule for action parameters of typeIFormFile andIFormFileCollection. Themultipart/form-data
request content type is inferred for these types.To disable the default behavior, set theSuppressConsumesConstraintForFormFileParameters property totrue
inStartup.ConfigureServices
:
services.Configure<ApiBehaviorOptions>(options =>{ options.SuppressConsumesConstraintForFormFileParameters = true; options.SuppressInferBindingSourcesForParameters = true; options.SuppressModelStateInvalidFilter = true;});
When the compatibility version is 2.2 or later, MVC transforms an error result (a result with status code 400 or higher) to a result withProblemDetails. TheProblemDetails
type is based on theRFC 7807 specification for providing machine-readable error details in an HTTP response.Consider the following code in a controller action:
if (pet == null){ return NotFound();}
TheNotFound
method produces an HTTP 404 status code with aProblemDetails
body. For example:
{ type: "https://tools.ietf.org/html/rfc7231#section-6.5.4", title: "Not Found", status: 404, traceId: "0HLHLV31KRN83:00000001"}
The automatic creation of aProblemDetails
for error status codes is disabled when theSuppressMapClientErrors property is set totrue
. Add the following code inStartup.ConfigureServices
:
By default, an action supports all available request content types. For example, if an app is configured to support both JSON and XMLinput formatters, an action supports multiple content types, includingapplication/json
andapplication/xml
.
The[Consumes] attribute allows an action to limit the supported request content types. Apply the[Consumes]
attribute to an action or controller, specifying one or more content types:
[HttpPost][Consumes("application/xml")]public IActionResult CreateProduct(Product product)
In the preceding code, theCreateProduct
action specifies the content typeapplication/xml
. Requests routed to this action must specify aContent-Type
header ofapplication/xml
. Requests that don't specify aContent-Type
header ofapplication/xml
result in a415 Unsupported Media Type response.The[Consumes]
attribute also allows an action to influence its selection based on an incoming request's content type by applying a type constraint. Consider 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 });}
In the preceding code,ConsumesController
is configured to handle requests sent to thehttps://localhost:5001/api/Consumes
URL. Both of the controller's actions,PostJson
andPostForm
, handle POST requests with the same URL. Without the[Consumes]
attribute applying a type constraint, an ambiguous match exception is thrown.The[Consumes]
attribute is applied to both actions. ThePostJson
action handles requests sent with aContent-Type
header ofapplication/json
. ThePostForm
action handles requests sent with aContent-Type
header ofapplication/x-www-form-urlencoded
.
Was this page helpful?
Was this page helpful?