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<T>
{
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<ValidationResult> ValidationResults = new List<ValidationResult>();
public FileUpload(byte[] buffer, string mediaType, string fileName, string value)
{
Buffer = buffer;
MediaType = mediaType;
FileName = fileName.Replace("\"","");
_RawValue = value;
Value = JsonConvert.DeserializeObject<T>(_RawValue);
foreach (PropertyInfo Property in Value.GetType().GetProperties())
{
var Results = new List<ValidationResult>();
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);
}
}
You can either write a custom MediaTypeFormatter
to facilitate your scenario or you can pull the data out of the request by hand using MultipartFormDataStreamProvider.FormData.AllKeys
collection. This way you can post both the file(s) and additional fields in one request.
A good tutorial by Mike Wasson is available here: http://www.asp.net/web-api/overview/working-with-http/sending-html-form-data,-part-2