首页 > 解决方案 > 为什么此字符串未绑定到 ASP.NET .Core API 操作中的文件名参数?

问题描述

我正在使用以下标头和正文测试带有提琴手的 API,并在以下位置发布http://localhost:50063/api/image

User-Agent: Fiddler
Content-Type: application/json; charset=utf-8
Host: localhost:50063
Content-Length: 32330

{"filename": "bot.png", "file": "base64 image ellided for brevity"}

教程中的示例代码

[ApiController]
[Produces("application/json")]
[Route("api/Image")]
public class ImageController : Controller
{

    // POST: api/image
    [HttpPost]
    public void Post(byte[] file, string filename)
    {
        string filePath = Path.Combine(_env.ContentRootPath, "wwwroot/images/upload", filename);
        if (System.IO.File.Exists(filePath)) return;
        System.IO.File.WriteAllBytes(filePath, file);
    }

    //...

}

首先,我收到错误 500,文件名为空。我将[ApiController]Attribute 添加到控制器类,我得到错误400 filename invalid

当我在这里提出相同的请求时,filename绑定到复杂类:

    [HttpPost("Profile")]
    public void SaveProfile(ProfileViewModel model)
    {
        string filePath = Path.Combine(_env.ContentRootPath, "wwwroot/images/upload", model.FileName);
        if (System.IO.File.Exists(model.FileName)) return;
        System.IO.File.WriteAllBytes(filePath, model.File);
    }

    public class ProfileViewModel
    {
        public byte[] File { get; set; }
        public string FileName { get; set; }
    }

为什么会这样?

标签: c#asp.net-coreasp.net-core-webapiparameterbinding

解决方案


请求内容只能从正文中读取一次。

在第一个示例中,填充数组后,它可以填充字符串,因为正文已被读取。

在第二个示例中,它在主体的一次读取中填充模型。

一旦为参数读取了请求流,通常不可能再次读取请求流以绑定其他参数。

ASP.NET Core 中的参考模型绑定


推荐阅读