ASP.NET Core API Controller:Response.Body.WriteAsync base64字符串无法正常工作
我正在尝试从API控制器返回表示jpeg图像的base64字符串,并将其设置为的src,但我的所有尝试都失败了。
这是非常简单的HTML:
而我的控制器:
[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
,在字符串中或不是,但没有任何工作。
我在这里和这里看到,在Response体流中写作是可行的,所以我认为我的方法很好(我之前尝试过返回一个简单的字符串,但不能正常工作)。
是的,我的base64字符串是正确的,因为我也试图将它直接包含在HTML中,图像显示正确。
我确切地说我不想使用任何JavaScript或Razor视图来实现这一点,只有纯HTML和我的控制器。
另请注意我在API控制器中。 我不能像我们在一个空的ASP.NET核心项目的Startup
类中的Configure
方法中看到的那样做:
app.Run(async (context) => { await context.Response.WriteAsync("Hello World!"); });
尽管两个响应的类型都是HttpResponse
,但我的控制器中的类型没有任何Response.WriteAsync
但是Response.Body.WriteAsync
感谢您的帮助,我正在搜索几个小时,但对于ASP.NET Core几乎没有相关资源
您仍然将数据作为base64文本返回,基本上 – 您将获得UTF-8编码forms,但这就是全部。
如果你真的只有图像的base64版本,你只需要解码:
byte[] image = Convert.FromBase64String(_base64Image2); await Response.Body.WriteAsync(image, 0, image.Length);
(请注意,它只需要您转换的base64 – 而不是数据URI。)