4

我在名为“Upload”的控制器中有一个带有参数HttpPostedFileBase对象的方法,我从视图中发布了文件并将其成功保存到文件夹中。但是当我尝试返回具有以下内容的 JSON 字符串对象时,它会引发异常并显示消息:

“从‘System.Web.HttpInputStream’上的‘ReadTimeout’获取值时出错。”

如果我删除了'files = files'行,它会正确返回。但我需要这些数据

public string Upload(HttpPostedFileBase files)
{
    try
    {          
        if (files != null && files.ContentLength > 0)
        {
            var path = Path.Combine(Server.MapPath("~/Uploads"), files.FileName);
            files.SaveAs(path);
            return JsonConvert.SerializeObject(
                new
            {
                files=files,
                Passed = true,
                Mesaj = "item added"
            });
        }
    }
}
4

1 回答 1

9

您可以像这样创建自定义 JsonConverter:

public class HttpPostedFileConverter : JsonConverter
{
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            var stream = (Stream)value;
            using (var sr = new BinaryReader(stream))
            {
                var buffer = sr.ReadBytes((int)stream.Length);
                writer.WriteValue(Convert.ToBase64String(buffer));
            }
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }

        public override bool CanRead
        {
            get { return false; }
        }

        public override bool CanConvert(Type objectType)
        {
            return objectType.IsSubclassOf(typeof(Stream));
        }
    }

并将其传递给 JsonConvert.SerializeObject 方法

return JsonConvert.SerializeObject(
                    new
                    {
                        files=files,
                        Passed = true,
                        Mesaj = "item added"
                    }, 
                    new HttpPostedFileConverter());
于 2015-10-11T22:04:03.670 回答