c# - 如何使用 HttpPostedFileBase 从 MVC 添加图片到 Web API?

标签 c# asp.net asp.net-mvc asp.net-web-api

我在项目中使用 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!";
        }
    }

enter image description here

最佳答案

发生此错误的原因是 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/

相关文章:

asp.net - 阿拉伯语查询字符串问题(???在值中)

asp.net - Action 方法不适用于asp.net MVC中的[HttpPost]属性

c# - 使用 Entity Framework 连接到数据库时出现错误

c# - 如何降低 IL 嵌套深度?

C# LINQ TO XML - 从 DTD header 中删除 "[]"个字符

c# - 如何编写正确的语法以从 C# 代码重命名 SQL Server 数据库表?

c# - ASP.NET Webforms .NET 4.0 中的路由 - GetVirtualPath 返回 null

css - 如何正确加载我的 css asp.net Visual Basic

ASP.NET MVC url搜索参数不带问号

javascript - Google oAuth - 在 JS 中验证用户,但在 C# 中使用