Web API Model Binding with Multipart formdata

前端 未结 2 577
醉酒成梦
醉酒成梦 2020-12-05 07:35

Is there a way to be able to get model binding (or whatever) to give out the model from a multipart form data request in ASP.NET MVC Web API?

I see

2条回答
  •  自闭症患者
    2020-12-05 08:10

    @Mark Jones linked over to my blog post http://lonetechie.com/2012/09/23/web-api-generic-mediatypeformatter-for-file-upload/ which led me here. I got to thinking about how to do what you want.

    I believe if you combine my method along with TryValidateProperty() you should be able accomplish what you need. My method will get an object deserialized, however it does not handle any validation. You would need to possibly use reflection to loop through the properties of the object then manually call TryValidateProperty() on each one. This method it is a little more hands on but I'm not sure how else to do it.

    http://msdn.microsoft.com/en-us/library/dd382181.aspx http://www.codeproject.com/Questions/310997/TryValidateProperty-not-work-with-generic-function

    Edit: Someone else asked this question and I decided to code it just to make sure it would work. Here is my updated code from my blog with validation checks.

    public class FileUpload
    {
        private readonly string _RawValue;
    
        public T Value { get; set; }
        public string FileName { get; set; }
        public string MediaType { get; set; }
        public byte[] Buffer { get; set; }
    
        public List ValidationResults = new List(); 
    
        public FileUpload(byte[] buffer, string mediaType, 
                          string fileName, string value)
        {
            Buffer = buffer;
            MediaType = mediaType;
            FileName = fileName.Replace("\"","");
            _RawValue = value;
    
            Value = JsonConvert.DeserializeObject(_RawValue);
    
            foreach (PropertyInfo Property in Value.GetType().GetProperties())
            {
                var Results = new List();
                Validator.TryValidateProperty(Property.GetValue(Value),
                                              new ValidationContext(Value) 
                                              {MemberName = Property.Name}, Results);
                ValidationResults.AddRange(Results);
            }
        }
    
        public void Save(string path, int userId)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
    
            var SafeFileName = Md5Hash.GetSaltedFileName(userId,FileName);
            var NewPath = Path.Combine(path, SafeFileName);
    
            if (File.Exists(NewPath))
            {
                File.Delete(NewPath);
            }
    
            File.WriteAllBytes(NewPath, Buffer);
    
            var Property = Value.GetType().GetProperty("FileName");
            Property.SetValue(Value, SafeFileName, null);
        }
    }
    

提交回复
热议问题