从WebApi返回图像

Wad*_*ira 6 c# asp.net-web-api

我正在制作Web Api,我需要将多个图像返回给客户端.我目前正在为每个图像使用Base64字符串,但这导致每个请求花费的时间太长.是否有更好,更有效的图像返回方式?

这是我正在使用的代码:

控制器:

    public LearningUnits GetLearningUnits([FromODataUri]Guid key)
    {
        var record = db.LearningUnits.SingleOrDefault(inst => inst.LearningUnitId == key);

        record.ImageURLPath = ImageHandler.ImageToByteArrayFromFilePath(record.ImageURLPath);

        return record;
    }
Run Code Online (Sandbox Code Playgroud)

ImageToByteArray方法:

    public static string ImageToByteArrayFromFilePath(string imagefilePath)
    {
        byte[] imageArray = File.ReadAllBytes(imagefilePath);

        string baseImage = Convert.ToBase64String(imageArray);

        return baseImage;
    }
Run Code Online (Sandbox Code Playgroud)

And*_*nge 0

解决方案是使用媒体格式化程序,这样当使用特定类型查询 Web API 时,您将收到该特定类型的实际二进制流。

http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters

这是标准的 RESTful 模式;你有相同的 URL,但当你想要数据的 JSON 记录时,你接受-type:application/json,但当你想要该媒体类型时,你将 MIME 请求类型更改为 image/png 或类似的类型。

更多信息请参见: 如何为 OData Api 提供自定义媒体类型格式

Odata 在这里也隐式支持它:https://msdn.microsoft.com/en-us/library/system.web.http.odata.formatter.odatamediatypeformatter (v=vs.118).aspx