1

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.

Dhwani
  • 7,484
  • 17
  • 78
  • 139

1 Answers1

2

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));
Dhwani
  • 7,484
  • 17
  • 78
  • 139
  • How can I secure `UserProfilePhoto`? Do you have any idea? Like in Mvc controller we use `[Authorize]`. Is there any way to secure ? – Ajay Feb 22 '15 at 09:58
  • @AjayPunekar I haven't try it but yes you can try this one: http://stackoverflow.com/a/10984570/1624583 – Dhwani Feb 23 '15 at 04:02
  • Ok thank you for reply. Yesterday I created one `ActionResult` to show user photo. But I am calling this `ActionResult` from controller. I have a question i.e. how can I call `UserProfilePhoto` class. I have built web api. I am trying to call `UserProfilePhoto` class from client side. How can I call ? – Ajay Feb 23 '15 at 05:45
  • @AjayPunekar as written in my question, Use Photo for displaying. And make sure u create your ashx file in the soluion, not in any folder of the solution. – Dhwani Feb 23 '15 at 05:58
  • Oh ok I have created this in folder. That's why I am not able to call this method. I will try. :) – Ajay Feb 23 '15 at 05:59