gpt4 book ai didi

c# - ASP.NET Core API Controller : Response. Body.WriteAsync base64 字符串不起作用

转载 作者:太空狗 更新时间:2023-10-29 18:24:28 26 4
gpt4 key购买 nike

我试图从 API Controller 返回表示 jpeg 图像的 base64 字符串,并将其设置为 <img> 的 src但我所有的尝试都失败了。

这是非常简单的 HTML:

<img src="/api/TestBase64Image" alt="image test" />

还有我的 Controller :

[Route("api/[controller]")]
public class TestBase64ImageController : Controller
{
private const string _base64Image = "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....";
private const string _base64Image2 = "/9j/4AAQSkZJRgABAQEBLAEsAAD/7Sfg.....";

[HttpGet]
public async Task Get()
{
Response.ContentType = "image/jpeg";
//Response.ContentType = "text/plain";
//Response.ContentType = new MediaTypeHeaderValue("image/jpeg").ToString();
//Response.ContentType = new MediaTypeHeaderValue("text/plain").ToString();

//Response.Headers.Add("Content-Length", _base64Image.Length.ToString());
//HttpContext.Response.ContentLength = _base64Image.Length;

await Response.Body.WriteAsync(Encoding.UTF8.GetBytes(_base64Image), 0, _base64Image.Length);
//await Response.Body.FlushAsync();
}
}

我尝试了几种方法,比如删除 FlushAsync() , 改变定义 ContentType 的方式, 包括 data:image/jpeg;base64 , 是否在字符串中,但没有任何效果。

我看过 herehere在 Response 正文流中写入是可行的,所以我认为我的方法很好(我之前尝试返回一个简单的字符串,但效果不佳)。

是的,我的 base64 字符串是正确的,因为我还尝试将它直接包含到 HTML 中并且图像正确显示。

确切地说,我不想使用任何 JavaScript 或 Razor View 来实现这一点,只使用纯 HTML 和我的 Controller 。

另请注意,我在 API Controller 中。我不能像我们在 Configure 中看到的那样做Startup 中的方法一个空的 ASP.NET Core 项目的类,例如:

app.Run(async (context) =>
{
await context.Response.WriteAsync("Hello World!");
});

即使两个响应的类型都是 HttpResponse ,我 Controller 中的那个没有任何 Response.WriteAsync但是Response.Body.WriteAsync

感谢您的帮助,我已经搜索了几个小时,但几乎没有关于 ASP.NET Core 的资源

最佳答案

您仍然以 base64 文本形式返回数据,基本上 - 您得到的是 UTF-8 编码形式,但仅此而已。

如果你真的只有图像的 base64 版本,你只需要解码它:

byte[] image = Convert.FromBase64String(_base64Image2);
await Response.Body.WriteAsync(image, 0, image.Length);

(请注意,它必须只是您转换的 base64,而不是数据 URI。)

关于c# - ASP.NET Core API Controller : Response. Body.WriteAsync base64 字符串不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39994695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com