Created
October 13, 2011 07:13
-
-
Save SimonCropp/1283627 to your computer and use it in GitHub Desktop.
nancy AsUnSafeFile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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