Skip to content

Instantly share code, notes, and snippets.

@janhebnes
Last active June 20, 2016 11:06
Show Gist options
  • Save janhebnes/72633a28a7a08199b708e43b314641fa to your computer and use it in GitHub Desktop.
Save janhebnes/72633a28a7a08199b708e43b314641fa to your computer and use it in GitHub Desktop.
HttpHandler that helps respect the Request flow and serves the default documents of a directory instead of allowing e.g. Umbraco to kidnap the request for there purposes.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
/// <summary>
/// Respect the DefaultDocuments even when Umbraco takes over the HttpModule pipeline
/// Add file to App_Code (or compile with your project) and
/// Add to web.config on system.web > httpModules add name="MyDefaultDocumentsHttpModule" type="DefaultDocumentsHttpModule"
/// Add to web.config on system.webServer > modules add name="MyDefaultDocumentsHttpModule" type="DefaultDocumentsHttpModule"
/// </summary>
public class DefaultDocumentsHttpModule : IHttpModule
{
#region IHttpModule Members
public void Init(HttpApplication context)
{
context.BeginRequest += ProcessRequest;
}
public void Dispose() { }
#endregion
protected void ProcessRequest(object sender, EventArgs e)
{
DefaultDocuments();
}
static void DefaultDocuments()
{
HttpContext context = HttpContext.Current;
HttpRequest request = context.Request;
var lastsegment = request.Url.Segments.LastOrDefault();
if (lastsegment != null && !lastsegment.Contains("."))
{
if (!IsDirectory(request.MapPath(request.Path))) return;
var separator = lastsegment.EndsWith("/") ? "" : "/";
var root = request.Path + separator;
if (IsFile(request.MapPath(root + "default.htm"))) // Hardcoded for avoiding to many IO operations e.g. reading settings
{
if (separator == "/") context.Response.Redirect(root,true); // Required for correct handling of relative page content /xxx is not the same content as /xxx/
context.RewritePath(root + "default.htm");
return;
}
if (IsFile(request.MapPath(root + "default.asp")))
{
if (separator == "/") context.Response.Redirect(root,true);
context.RewritePath(root + "default.asp");
return;
}
if (IsFile(request.MapPath(root + "index.html")))
{
if (separator == "/") context.Response.Redirect(root,true);
context.RewritePath(root + "index.html");
return;
}
}
return;
}
private static bool IsFile(string mapPath)
{
return System.IO.File.Exists(mapPath);
}
private static bool IsDirectory(string mapPath)
{
return System.IO.Directory.Exists(mapPath);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment