POST actions in [ApiController] in ASP.NET Core 2.1

荒凉一梦 提交于 2020-01-03 17:24:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!