代码之家  ›  专栏  ›  技术社区  ›  user5389726598465

为什么这个字符串没有绑定到ASP.NET.CORE API操作中的文件名参数?

  •  2
  • user5389726598465  · 技术社区  · 6 年前

    我正在用fiddler测试一个API,使用下面的header和body并在 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"}
    

    示例代码来自 tutorial

    [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] 属性到控制器类,我得到错误 400文件名无效 .

    当我在这里提出同样的要求时, 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; }
        }
    

    为什么会这样?

    1 回复  |  直到 6 年前
        1
  •  2
  •   Nkosi    6 年前

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

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

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

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

    参考 Model Binding in ASP.NET Core