Testing out Web API for file uploading, have a simple view model like this:
public class TestModel {
public string UserId {get;set;}
public HttpPoste
See my original answer https://stackoverflow.com/a/12603828/1171321
Basically combine my method in my blog post and the TryValidateProperty() suggestion to maintain model validation annotations.
Edit: I went ahead and worked up a code enhancement to my code in the blog post. I'm going to post this updated code shortly. Here is a simple example that validates each property and gives you access to an array of the results. Just a sample of one approach
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);
}
}