gpt4 book ai didi

c# - 将 ASP .NET MVC ActionResult 呈现为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 15:33:41 25 4
gpt4 key购买 nike

我正在尝试将 FileContentResult(在我的例子中是 .png 文件)呈现为 base64 字符串,以将它们返回到 json 中。

我从这里找到了一个有趣的方法:http://approache.com/blog/render-any-aspnet-mvc-actionresult-to/ ,那应该是在做我需要的,但是当我试图做类似的事情时

public async ActionResult GetUsers()
{
...
var query = from user in otherUsers
join file in allFiles on user.Profile.Id equals file.Profile.Id into usersWithFiles
from userWithFile in usersWithFiles.DefaultIfEmpty(new File(){Content = new byte[0], ContentType = "image/png"})
select new UserFriendModel { Id = user.Id, UserName = user.UserName, ProfileId = user.Profile.Id, File = File(userWithFile.Content, userWithFile.ContentType).Capture(ControllerContext) };

return Json(query.ToList(), JsonRequestBehavior.AllowGet);
}

我得到了

System.Web.HttpException:"OutputStream is not available when a custom TextWriter is used" thrown at result.ExecuteResult(controllerContext); line.

最佳答案

您可以在单独的查询中获取文件(png 图像),使用您的文本编写器将数据转换为文本格式,然后将其注入(inject)您的数据模型。

像这样的一些伪代码:

var file = GetFileQuery();
var fileString = TextWriter.Convert(file);
var query = from user in otherUsers
join file in allFiles on user.Profile.Id equals file.Profile.Id into usersWithFiles
from userWithFile in usersWithFiles.DefaultIfEmpty(new File(){Content = new byte[0], ContentType = "image/png"})
select new UserFriendModel { Id = user.Id, UserName = user.UserName, ProfileId = user.Profile.Id, File = fileString };

另一种方法是使用 2 个不同的操作来处理请求。第一个操作返回数据模型的所有正常数据,第二个操作只返回图像。通过这种方式,您可以更灵活地使用图像格式,即您可以在 OutputStream 中将其作为 PNG 图像返回(无需显式序列化/反序列化)。

那是我的 2 美分。

亨利

关于c# - 将 ASP .NET MVC ActionResult 呈现为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32703341/

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