Skip to content

Instantly share code, notes, and snippets.

@SimonCropp
Created October 13, 2011 07:13
Show Gist options
  • Save SimonCropp/1283627 to your computer and use it in GitHub Desktop.
Save SimonCropp/1283627 to your computer and use it in GitHub Desktop.
nancy AsUnSafeFile
public static class FormatterExtensions
{
public static Response AsUnSafeFile(this IResponseFormatter formatter, string filePath, Request request)
{
if (string.IsNullOrWhiteSpace(filePath))
{
throw new Exception("filePath not defiend");
}
if (!File.Exists(filePath))
{
return HttpStatusCode.NotFound;
}
var lastWriteTimeUtc = File.GetLastWriteTimeUtc(filePath);
var currentFileEtag = lastWriteTimeUtc.Ticks.ToString("x");
var etagHeaders = request.Headers["ETag"];
if (etagHeaders != null)
{
var requestEtag = etagHeaders.FirstOrDefault();
if (requestEtag == currentFileEtag)
{
return HttpStatusCode.NotModified;
}
}
var ifModifiedSinceHeaders = request.Headers["If-Modified-Since"];
var lastWriteTimeAsString = lastWriteTimeUtc.ToString("R");
if (ifModifiedSinceHeaders != null)
{
var requestIfModifiedSinceHeader = ifModifiedSinceHeaders.FirstOrDefault();
if (lastWriteTimeAsString == requestIfModifiedSinceHeader)
{
return HttpStatusCode.NotModified;
}
}
//Cant use as file cause it validates the location of the file and we are using a network share.
var response = new SimpleFileResponse(filePath, "application/json");
response.Headers["ETag"] = currentFileEtag;
response.Headers["Last-Modified"] = lastWriteTimeAsString;
return response;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment