问题
I have the following ASP.NET Core 2.1 Api controller:
[Route("api/[controller]")]
[ApiController]
public class ImagesController : ControllerBase
{
[HttpPost("[action]")]
public async Task<IActionResult> Upload([FromForm]ICollection<IFormFile> files)
{ ... }
[HttpGet("thumbnails")]
public async Task<IActionResult> GetThumbNails()
{ ... }
Both the GET and POST actions worked with Postman.
However, the POST action would not work with the UI: the action would always receive a files parameter count of 0 (see here for full details of the fault).
I eventually fixed the fault by removing the [ApiController]
attribute from the controller:
[Route("api/[controller]")]
//[ApiController]
public class ImagesController : ControllerBase
{ ... }
My question is why did the [ApiController]
controller attribute prevent the POST method from receiving the files from the UI? What is happening here? Is it a routing problem?
回答1:
You need to set the compatibility version:
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
According to https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.1
回答2:
The ApiController Attribute was added in ASP.NET Core 2.1 and includes binding source parameter inference. There is a recent commit to Infer BindingSource.FormFile for IEnumerable which may be related.
来源:https://stackoverflow.com/questions/50919430/post-actions-in-apicontroller-in-asp-net-core-2-1