Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
564 views
in Technique[技术] by (71.8m points)

asynchronous - How create a MultipartFormFormatter for ASP.NET 4.5 Web API

These links didn't help me:

Example:

//Model:
public class Group
{
    public int Id { get; set; }        
    public File File { get; set; }
}

//Controller:
[HttpPost]
public void SaveGroup([FromBody]Group group) {}

//Formatter:
public class MultipartFormFormatter : MediaTypeFormatter
{
    private const string StringMultipartMediaType = "multipart/form-data";

    public MultipartFormFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));

    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }

    public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        //Implementation? What here should be?
    }       
}

What should the method ReadFromStreamAsync return?

How do I make it so that you can properly transmit parameter to the action?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
public class MultipartFormFormatter : FormUrlEncodedMediaTypeFormatter
{
    private const string StringMultipartMediaType = "multipart/form-data";
    private const string StringApplicationMediaType = "application/octet-stream";

    public MultipartFormFormatter()
    {
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringMultipartMediaType));
        this.SupportedMediaTypes.Add(new MediaTypeHeaderValue(StringApplicationMediaType));
    }

    public override bool CanReadType(Type type)
    {
        return true;
    }

    public override bool CanWriteType(Type type)
    {
        return false;
    }

    public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
    {
        var parts = await content.ReadAsMultipartAsync();
        var obj = Activator.CreateInstance(type);
        var propertiesFromObj = obj.GetType().GetRuntimeProperties().ToList();

        foreach (var property in propertiesFromObj.Where(x => x.PropertyType == typeof(FileModel)))
        {
            var file = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));

            if (file == null || file.Headers.ContentLength <= 0) continue;

            try
            {
                var fileModel = new FileModel(file.Headers.ContentDisposition.FileName, Convert.ToInt32(file.Headers.ContentLength), ReadFully(file.ReadAsStreamAsync().Result));
                property.SetValue(obj, fileModel);
            }
            catch (Exception e)
            {
            }
        }

        foreach (var property in propertiesFromObj.Where(x => x.PropertyType != typeof(FileModel)))
        {
            var formData = parts.Contents.FirstOrDefault(x => x.Headers.ContentDisposition.Name.Contains(property.Name));

            if (formData == null) continue;

            try
            {
                var strValue = formData.ReadAsStringAsync().Result;
                var valueType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                var value = Convert.ChangeType(strValue, valueType);
                property.SetValue(obj, value);
            }
            catch (Exception e)
            {
            }
        }

        return obj;
    }

    private byte[] ReadFully(Stream input)
    {
        var buffer = new byte[16 * 1024];
        using (var ms = new MemoryStream())
        {
            int read;
            while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
            {
                ms.Write(buffer, 0, read);
            }
            return ms.ToArray();
        }
    }
}

public class FileModel
{
    public FileModel(string filename, int contentLength, byte[] content)
    {
        Filename = filename;
        ContentLength = contentLength;
        Content = content;
    }

    public string Filename { get; set; }

    public int ContentLength { get; set; }

    public byte[] Content { get; set; }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...