c# - 从 WebApi 返回图像

标签 c# asp.net-web-api

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

这是我使用的代码:

Controller :

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

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

        return record;
    }

ImageToByteArray 方法:

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

        string baseImage = Convert.ToBase64String(imageArray);

        return baseImage;
    }

最佳答案

如果端点返回 json,那么除了 base64 之外,没有其他方法可以在响应中嵌入二进制文件。但由于性能问题,这绝对不是一个好主意。可能对于某些图标来说没问题,但对于较大的图像就不合适了。

所以这里最好的解决方案是将 url 返回到图像。客户端将进一步请求获取图像的原始字节。

另外值得一提的是,图像 url 不仅可以是静态文件的路径,还可以是一些 webapi 端点的路径,例如,通过资源 id 获取图像字节并发送客户端原始二进制文件返回,而不是 json 字符串。

关于c# - 从 WebApi 返回图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770334/

相关文章:

c# - 调试异步ASP.NET Web API Controller 在“任务”窗口中显示 "No tasks to display"

c# - 为 Editor For 添加样式

c# - 是::用于 "global::"以外的任何内容

c# - 如何在 Windows 应用程序中双向绑定(bind)对象到组合框

c# - Thread.Sleep( ) 确保 DateTime.Now 不同所需的最短时间是多少?

c# - 当 localhost :port number is in browser address in iis express 时,web api 显示 403.14 错误

c# - 在 Web API 中返回 JSON

.net - 如何在 ASP.NET Core 测试中 stub /模拟服务

c# - TempData 在 ASP.Net Core 2.1 MVC 中始终为 Null

c# - 使用 Http.RouteAttribute 路由可选参数