I am trying to write an HTTP handler in C# that loads images from a network drive and writes them to the HTTP response. This is currently not working for me as I keep getting HTTP 302 responses which results in the broken file image being displayed. Below is my HTTP handler. Access permissions have been set so anonymous users have read access to the share but ideally this will not be permanent.
public class SecCamImage : IHttpHandler, IRequiresSessionState
{
public void ProcessRequest(HttpContext context)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~/Web.Config");
KeyValueConfigurationElement setting = null;
if(config.AppSettings.Settings.Count > 0)
{
setting = config.AppSettings.Settings["CameraBaseURL"];
}
if(setting != null)
{
string baseURL = setting.Value;
string location = context.Request["location"].ToString();
string camera = context.Request["camera"].ToString();
string image = context.Request["image"].ToString();
if (!(string.Compare(image, "no-image.jpg", true) == 0))
{
if (!string.IsNullOrEmpty(location) && !string.IsNullOrEmpty(camera) && !string.IsNullOrEmpty(image))
{
string fullPath = string.Format(baseURL, location, camera, image);
System.IO.FileInfo imageFile = new System.IO.FileInfo(fullPath);
if (imageFile.Exists)
{
if (context.User.Identity.IsAuthenticated)
{
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(imageFile.FullName);
context.Response.End();
}
}
}
}
else
{
context.Response.ContentType = "image/jpeg";
context.Response.WriteFile(image);
context.Response.End();
}
}
}
public bool IsReusable
{
get { return false; }
}
}
The URL stored in the config file is structured like this:-
\\\\host\\directory\\{0}\\{1}\\{2}
{0}
and {1}
are directories and {2}
is the file.
I managed to get this working by adding a Virtual Directory to our Website on IIS. The .ashx handler now references the Virutal Directory and not the directory on the network drive.