Return 图片为 url 来自 .net 5 web api

Return Image as url from .net 5 web api

我想从我的控制器return图像url。

我有一个字节数组(图片)。

我不想 return 作为基数 64。

我想return它作为

http://localhost:6548/image/myimage.png

我该怎么做?

我的游乐场代码 - 对我不起作用。

public HttpResponseMessage ImageLink()
        {
            var images = _context.Set<Image>();
            var image = images.FirstOrDefault(x => x.Id == 1);
            //return File(image.Data, "image/jpeg");
            HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
            result.Content = new ByteArrayContent(image.Data);
            result.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");
            return result;
        }

你可以做的是将 base64 转换为二进制流,然后将其保存在同一个应用程序中的图像文件夹中,然后 return URL 作为字符串,在这种情况下,URL 将可访问。

控制器代码如下

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;

namespace MyNameSpace
{
    public class TestController : Controller
    {
        private readonly IWebHostEnvironment _webHostEnvironment;
        public TestController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }
        public IActionResult ImageLink()
        {
            byte[] file_bytes = Convert.FromBase64String("base 64 string");
            string webRootPath = _webHostEnvironment.WebRootPath;
            string imagePath  = Path.Combine(webRootPath, "image/myimage.png");
            System.IO.File.WriteAllBytes(imagePath, file_bytes);
            return Ok("http://localhost:6548/image/myimage.png");
        }

    }
}