Serving Images from an Image Controller

Found this solution rather simple when you want to serve images from your database.

public class ImageController
{
	readonly IImageQueries Queries;

	public ImageController(IImageQueries queries)
	{
		Queries = queries;
	}

	public FileResult Show(int id)
	{
		DateTime? dateCreated = Queries.GetDateCreatedById(id);

		//invalid image, return 404
		if (dateCreated == null)
		{
			HttpContext.Response.StatusCode = 404;

			return null;
		}
		else
		{
			string ifModifiedSince = HttpContext.Request.Headers["If-Modified-Since"];

			//check if image has been modified
			if (ifModifiedSince != null && dateCreated.Value <= DateTime.Parse(ifModifiedSince))
			{
				HttpContext.Response.StatusCode = 304;
				return null;
			}
			else
			{
				HttpContext.Response.Cache.SetLastModified(dateCreated.Value);

				dynamic image = Queries.GetById(id);

				return new FileContentResult(image.Bytes, image.MimeType);
			}
		}
	}
}

Related Articles:

Post Footer automatically generated by Add Post Footer Plugin for wordpress.

About Sean Biefeld

Hello all, my name is Sean Biefeld. I graduated from Baylor University with a BBA in Management Information Systems. I am currently working for McLane Advanced Technologies . The opinions expressed by me, however accurate they may be, are not necessarily those of my employer. I have been a developing software professionally since 2004. My primary development focus is on HTML, CSS, JavaScript and C#. I dabble in a little PHP and Ruby. This blog is a forum for me to post my experiences, ideas, rants, and thoughts as I traverse the mountain of life.
This entry was posted in .NET, ASP.NET MVC, C#. Bookmark the permalink. Follow any comments here with the RSS feed for this post.