渲染asp.net MVC ActionResult为字符串

本文关键字:字符串 ActionResult MVC asp net 渲染 | 更新日期: 2023-09-27 18:13:53

我试图渲染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);
}

I'm getting

包含。HttpException:"OutputStream是不可用的在result.ExecuteResult(controllerContext)抛出;线。

渲染asp.net MVC ActionResult为字符串

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

一些psudo代码如下:

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 };

另一种方法是使用两个不同的操作来处理请求。第一个操作返回数据模型的所有正常数据,第二个操作只返回图像。这样你可以更灵活地使用你的图像格式,也就是说,你可以在OutputStream中返回PNG图像(没有显式的序列化/反序列化)。

这是我的2美分。

亨利