我在项目中使用 Web API,但当我尝试向员工添加图片时遇到问题,所有数据注册正常,只有图片出现错误。 在其他项目中工作正常,但使用 Web API 我无法添加它。
错误:
JsonSerializationException: Error getting value from 'ReadTimeout' on 'System.Web.HttpInputStream'.
我的模型:
public class EmployeeViewModel
{
public int Id { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[Required]
[StringLength(50)]
public string CPF { get; set; }
[StringLength(50)]
public string City { get; set; }
[Required]
[StringLength(50)]
public string Adress { get; set; }
public int OcupationId { get; set; }
[Required]
[StringLength(100)]
public string Picture { get; set; }
public virtual Occupation Occupation { get; set; }
public HttpPostedFileBase Pic { get; set; }
}
我的 Controller :
[HttpPost]
public ActionResult AddOrEdit(EmployeeViewModel employee)
{
if (employee.Id == 0)
{
if (employee.Pic != null)
{
var pic = Ultilidades.UploadPhoto(employee.Pic);
if (!string.IsNullOrEmpty(pic))
{
employee.Picture = string.Format("~/Content/Pictures/{0}", pic);
}
}
HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Employee",employee).Result;
TempData["SuccessMessage"] = "sucess!";
}
}
最佳答案
发生此错误的原因是 PostAsJsonAsync
方法尝试序列化HttpInputStream
对象作为字符串而不是字节数组(请注意,JSON 序列化程序对于数组而不是流效果更好)。您可以创建另一个专门为 Web API 设计的模型类,其中包含重复的 int
& string
来自 MVC View 模型的属性以及要存储的附加字节数组属性 HttpPostedFileBase
像这样的对象:
public class EmployeeWebApiModel
{
public int Id { get; set; }
// other properties
public string Picture { get; set; }
// byte array to hold HttpPostedFileBase content in Web API context
public byte[] PicData { get; set; }
}
使用上面定义的Web API模型类,然后阅读HttpPostedFileBase
对象并将其存储在字节数组属性 using BinaryReader
中,假设您已经使用 new
声明了模型关键字:
var apiModel = new EmployeeWebApiModel();
// other logic here
var br = new BinaryReader(employee.Pic.InputStream);
apiModel.PicData = br.ReadBytes(employee.Pic.ContentLength);
然后,您可以使用 PostAsJsonAsync
序列化 Web API 模型类:
HttpResponseMessage response = GlobalVariables.WebApiClient.PostAsJsonAsync("Employee", apiModel).Result;
可以找到类似的问题here (用 IEnumerable<HttpPostedFileBase>
而不是单个 HttpPostedFileBase
)。
关于c# - 如何使用 HttpPostedFileBase 从 MVC 添加图片到 Web API?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49601929/