【问题标题】:.net core web api upload file fail with badrequest.net core web api上传文件失败,请求错误
【发布时间】:2020-01-13 17:38:18
【问题描述】:

我正在尝试使用 .net core 2.1 web api 将几个文件上传到 web api 端点

这是我的控制器和上传方法

[Produces("application/json")]
[Route("api/[controller]")]
[ApiController]
public class PagosController : ControllerBase{
        [HttpPost("UploadDescuento")]
        public async Task<IActionResult> UploadDescuento(IEnumerable<IFormFile> files)
        {

            return Ok();
        }
}

我通过邮递员向控制器发出请求,但收到错误请求 第一次我认为我的要求很糟糕,所以我在邮递员中做了同样的要求

POST /api/pagos/UploadDescuento HTTP/1.1
Host: localhost:59039
User-Agent: PostmanRuntime/7.16.3
Accept: */*
Cache-Control: no-cache
Postman-Token: 7535f283-89fb-4f86-bbb9-3d78ec302ebe,19a709dd-37c9-48ef-a157-c21f99861260
Host: localhost:59039
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW
Accept-Encoding: gzip, deflate
Content-Length: 1320022
Connection: keep-alive
cache-control: no-cache


Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/0-5616x3744.jpg


------WebKitFormBoundary7MA4YWxkTrZu0gW--,
Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/0-5616x3744.jpg


------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures/101-2621x1747.jpg


------WebKitFormBoundary7MA4YWxkTrZu0gW--
Content-Disposition: form-data; name="pago"

234235834
------WebKitFormBoundary7MA4YWxkTrZu0gW--

但我收到了错误的请求

{
    "": [
        "The input was not valid."
    ]
}

【问题讨论】:

    标签: asp.net-core .net-core asp.net-core-webapi


    【解决方案1】:

    你需要在postman的body中选择form-data,并设置一个关键的“files”为文件类型example

    【讨论】:

    • 我想,我做到了,你可以在 Postman 创建的请求中看到 "Content-Disposition: form-data; name="files"; filename="/C:/Users/jcpc9/Pictures /101-2621x1747.jpg "
    • 选择从您的计算机上传特定文件,您将以字节形式发送文件,但不要仅以字符串形式发送文件的位置
    【解决方案2】:

    我的解决方案是删除 de 属性 ApiController 我不知道为什么文档没有说太多 [https://docs.microsoft.com/en-us/aspnet/core/web-api/?view=aspnetcore-2.2#multipartform-data-request-inference] 我不明白是什么问题

    [Produces("application/json")]
        [Route("api/[controller]")]
        //[ApiController]<<remove this
        public class PagosController : ControllerBase
    

    方法

    [HttpPost("UploadDescuento")]
    public async Task<IActionResult> UploadDescuento(IEnumerable<IFormFile> files)
    

    如果有人知道为什么这个属性“[ApiController]”会导致这个问题,我希望你能解释一下或者至少是一篇好文章

    【讨论】:

      【解决方案3】:

      您没有上传文件。您只是在客户端计算机上发送文件的路径,服务器无法对其执行任何操作(除非服务器和客户端计算机始终相同)。

      邮递员确实可以选择正确发送文件。见this answer

      【讨论】:

        猜你喜欢
        • 2020-03-12
        • 2022-09-30
        • 2021-11-27
        • 1970-01-01
        • 1970-01-01
        • 2019-10-29
        • 1970-01-01
        • 1970-01-01
        • 2017-05-12
        相关资源
        最近更新 更多