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);
			}
		}
	}
}
Dynamic View Page, MVC without a View Model