【问题标题】:Display base64 image using generic handler(ashx)使用通用处理程序(ashx)显示 base64 图像
【发布时间】:2015-02-02 13:13:14
【问题描述】:

我正在尝试使用通用处理程序显示 base64,但没有成功。这是我的通用处理程序代码:

public class UserProfilePhoto : IHttpHandler, IReadOnlySessionState
{
        public void ProcessRequest(HttpContext context)
        {
            try
            {

                if (UserSession.Get().UserPhoto == null)
                {
                    context.Response.ContentType = "image/png";
                    context.Response.WriteFile("~/assets/img/avatar.png");
                }
                else
                {
                    context.Response.ContentType = UserSession.Get().UserPhoto.Substring(0, UserSession.Get().UserPhoto.IndexOf(","));
                    context.Response.Write(UserSession.Get().UserPhoto);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool IsReusable
        {
            get
            {
                return true;
            }
        }
    }

在视图页面上调用如下:

<img alt="Photo" ng-src="UserProfilePhoto.ashx" />

它不会改变 img 标签的 src。我不知道出了什么问题。帮助。 Here is the base64 string which I am getting from database.

【问题讨论】:

标签: c# asp.net-mvc base64 ashx


【解决方案1】:

实际上问题出在我的 base64 字符串中。它添加了内容类型。所以我删除了它,它使用 BinaryWrite 工作正常。

context.Response.ContentType = UserSession.Get().UserPhoto.Substring(0, UserSession.Get().UserPhoto.IndexOf(","));
var imageBytes = UserSession.Get().UserPhoto.Substring(UserSession.Get().UserPhoto.IndexOf(",")+1);
context.Response.BinaryWrite(Convert.FromBase64String(imageBytes));

【讨论】:

  • 如何保护UserProfilePhoto?你有什么主意吗?就像在 Mvc 控制器中一样,我们使用[Authorize]。有什么方法可以保障吗?
  • @AjayPunekar 我没试过,但是你可以试试这个:stackoverflow.com/a/10984570/1624583
  • 好的,谢谢您的回复。昨天我创建了一个ActionResult 来展示用户照片。但我从控制器调用这个ActionResult。我有一个问题,即我怎样才能调用UserProfilePhoto 类。我已经建立了 web api。我正在尝试从客户端调用 UserProfilePhoto 类。我怎么打电话?
  • @AjayPunekar 正如我的问题中所写,使用 进行显示。并确保您在解决方案中创建 ashx 文件,而不是在解决方案的任何文件夹中。
  • 哦,好的,我已经在文件夹中创建了这个。这就是为什么我无法调用此方法的原因。我会尝试。 :)
猜你喜欢
  • 2012-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-03
  • 2013-03-16
  • 1970-01-01
相关资源
最近更新 更多