c# - 为什么此字符串未绑定到 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; }
}
为什么会这样?
解决方案
请求内容只能从正文中读取一次。
在第一个示例中,填充数组后,它可以填充字符串,因为正文已被读取。
在第二个示例中,它在主体的一次读取中填充模型。
一旦为参数读取了请求流,通常不可能再次读取请求流以绑定其他参数。
ASP.NET Core 中的参考模型绑定
推荐阅读
- python - 寻找一种更好的方法来为字典、全局整数生成键?
- graphics - Blender 如何解释 Collada 文件 (.dae) 以进行装配?
- c# - 如何从剃刀页面处理程序呈现视图?
- html - favicon.ico 在 IE 11 上不可见
- c# - 创建目录并允许写访问 C# .NET Core
- c# - Wcf 将整数值设置为默认值
- python - python从字典中写入csv,同时删除列表括号
- python - 以毫秒为单位将时间转换回时间戳 Python?
- regex - 你能帮我用一个正则表达式来匹配 1 个字符串中的 2 个不同部分作为一个组吗
- amazon-web-services - 权限被拒绝:'/home/ugurkaya/.aws/credentials'