0

我正在实现自定义 MediaTypeFormatter,并且在覆盖方法 ReadFromStreamAsync 上遇到编译错误,如代码示例中所示。不幸的是,出于工作原因,我无法更新到 Visual Studio 2012 并使用 .net 4.5:

ImageMediaFormatter.ReadFromStreamAsync(System.Type, System.IO.Stream, System.Net.Http.HttpContent, System.Net.Http.Formatting.IFormatterLogger)':并非所有代码路径都返回值

public class ImageMediaFormatter : MediaTypeFormatter
{
    public ImageMediaFormatter()
    {
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpeg"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/jpg"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("image/png"));
        SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
    }

    public override bool CanReadType(Type type)
    {
        return type == typeof(ImageMedia);
    }

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

    public override Task<object> ReadFromStreamAsync(
        Type type, Stream stream, HttpContent request,
        IFormatterLogger formatterContext)
    {

        if (!request.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        var streamProvider = new MultipartMemoryStreamProvider();
        var task = request.ReadAsMultipartAsync(streamProvider)
            .ContinueWith(
               t =>
               {
                   var content = streamProvider.Contents.First(x =>
                    SupportedMediaTypes.Contains(x.Headers.ContentType));

                   string fileName = content.Headers.ContentDisposition.FileName;
                   string mediaType = content.Headers.ContentType.MediaType;

                   var imgstream = content.ReadAsStreamAsync().ContinueWith(x =>
                                                                                {
                                                                                    byte[] imagebuffer = ReadFully(x.Result);
                                                                                    return new ImageMedia(fileName, mediaType, imagebuffer);  
                                                                                });




               }
         );

        //return task.Result;

    }

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

1 回答 1

1

好吧,该ReadFromStreamAsync()方法必须返回 aTask<object>但是您已经注释掉了该return语句(它可能应该只是return task;),所以显然它不会编译。

于 2013-07-13T11:15:58.433 回答