我有一个 webapi 项目,无法找到绑定(bind)上传文件内容的好方法。
我有一个 Entity Framework 模型如下:
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public UploadedFileId UploadedFileId { get; set; }
public virtual UploadedFile UploadedFile { get; set; }
}
上传的文件如下:
public class UploadedFile
{
public int Id { get; set; }
public byte[] Content { get; set; }
public string FileName { get; set; }
}
我在客户端上有一个 SPA,其中包含上传文件的表单,
在 Controller 中,我尝试让模型绑定(bind)与文件上传一起工作,但我的尝试都不起作用。
版本 1:
using System.Web.Http;
...
public IHttpActionResult Post(Person entity) {
/* some code */
}
这显然是行不通的,虽然模型本身是空的,但我不明白为什么。我期待它会绑定(bind)属性并忽略该文件。
版本 2:
public IHttpActionResult Post(Person entity, HttpPostedFileBase somefile) {
/* some code */
}
还尝试在客户端的表单输入中使用不同的名称(file、fileUpload、files、HttpPostedFile、HttpPostedFileBase)
版本 3:
public IHttpActionResult Post(HttpPostedFileBase somefile) {
/* some code */
}
somefile 在这里也是空的。
版本 4:尝试创建绑定(bind)
public class UploadedFilesModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpPostedFileBase file =controllerContext.HttpContext.Request.Files[bindingContext.ModelName];
var uploadFile = new UploadedFile();
uploadFile.FileName = file.FileName;
uploadFile.Content = new byte[(int)file.InputStream.Length];
file.InputStream.Read(uploadFile.Content, 0, (int)file.InputStream.Length);
return uploadFile;
}
}
全局.asax
ModelBinders.Binders[typeof(UploadedFile)] = new UploadedFilesModelBinder();
Controller
public IHttpActionResult Post(UploadedFile somefile) {
/* some code */
}
从未调用过自定义 Binder 。
我可以从上下文请求表单访问文件,但是模型非常复杂,这意味着我必须自己绑定(bind)它的属性。如果框架中已有 Binder ,我不想编写 Binder 。 有没有办法解决这个问题?
最佳答案
看看这个答案https://stackoverflow.com/a/19746825/2138959 .同样基于 Sending HTML Form Data in ASP.NET Web API: File Upload and Multipart MIME您可以读取多部分表单数据。第一部分代表模型,您可以使用媒体类型格式化程序映射到模型以避免手动属性映射,然后使用文件读取第二部分并将文件手动设置为模型。
关于c# - asp.net webapi 绑定(bind) ef 模型与文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42886119/