Search code examples
c#asp.net-mvcbase64ashx

Display base64 image using generic handler(ashx)


I am trying to display base64 using generic handler but not getting success. Here is my code of generic handler:

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

Calling on view-page like below:

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

It's not changing src of img tag. I don't know what is wrong. help. Here is the base64 string which I am getting from database.


Solution

  • Actually the problem was in my base64 string. It has content type added with it. So i removed it and it is working fine using 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));