How does one correctly implement a MediaTypeFormatter to handle requests of type 'multipart/mixed'?

前端 未结 2 754
感情败类
感情败类 2020-12-24 02:44

Consider a web service written in ASP.NET Web API to accept any number files as a \'multipart/mixed\' request. The helper method mat look as follows (assuming _client

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-24 03:03

    Have a look at this forum: http://forums.asp.net/t/1777847.aspx/1?MVC4+Beta+Web+API+and+multipart+form+data

    Here is a snippet of code (posted by imran_ku07) that might help you implement a custom formatter to handle the multipart/form-data:

    public class MultiFormDataMediaTypeFormatter : FormUrlEncodedMediaTypeFormatter
    {
        public MultiFormDataMediaTypeFormatter() : base()
        {
            this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
        }
    
        protected override bool CanReadType(Type type)
        {
            return true;
        }
    
        protected override bool CanWriteType(Type type)
        {
            return false;
        }
    
        protected override Task OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            var contents = formatterContext.Request.Content.ReadAsMultipartAsync().Result;
            return Task.Factory.StartNew(() =>
            {
                return new MultiFormKeyValueModel(contents);
            });
        }
    
        class MultiFormKeyValueModel : IKeyValueModel
        {
            IEnumerable _contents;
            public MultiFormKeyValueModel(IEnumerable contents)
            {
                _contents = contents;
            }
    
    
            public IEnumerable Keys
            {
                get
                {
                    return _contents.Cast();
                }
            }
    
            public bool TryGetValue(string key, out object value)
            {
                value = _contents.FirstDispositionNameOrDefault(key).ReadAsStringAsync().Result;
                return true;
            }
        }
    }
    
    
    

    You then need to add this formatter to your application. If doing self-host you can simply add it by including:

    config.Formatters.Insert(0, new MultiFormDataMediaTypeFormatter());
    

    before instantiating the HttpSelfHostServer class.

    -- EDIT --

    To parse binary streams you'll need another formatter. Here is one that I am using to parse images in one of my work projects.

    class JpegFormatter : MediaTypeFormatter
    {
        protected override bool CanReadType(Type type)
        {
            return (type == typeof(Binary));
        }
    
        protected override bool CanWriteType(Type type)
        {
            return false;
        }
    
        public JpegFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
            SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
        }
    
        protected override Task OnReadFromStreamAsync(Type type, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext)
        {
            return Task.Factory.StartNew(() =>
                {
                    byte[] fileBytes = new byte[stream.Length];
                    stream.Read(fileBytes, 0, (int)fileBytes.Length);
    
                   return (object)new Binary(fileBytes);
                }); 
        }
    
        protected override Task OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
        {
            throw new NotImplementedException();
        }
    }
    
    
    

    In your controller/action you'll want to do something along the lines of:

    public HttpResponseMessage UploadImage(Binary File) {
     //do something with your file
    }
    

    提交回复
    热议问题