I want to be able to return a 404 page when a resource doesn’t exist. At the same time, if a resource requires authentication, I want to be able to redirect the user to the login page. If I add code in RawHttpHandlers, do I need to check if a resource exists and handle 404 myself? What is the best way to do this?
Currently, I’m doing something like this:
// This should handle all 404's
CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new CustomStaticFileHandler("/404.html");
RawHttpHandlers.Add(httpReq =>
{
// Because of this, the above won't handle the 404 if my incorrect path has the extension in it
// which is why i handle it in the code below inside this block
if (httpReq.PathInfo.EndsWith(".html"))
{
if (!files.Any(s => httpReq.PathInfo.ToLower().Contains(s)))
{
var session = httpReq.GetSession();
if (!session.IsAuthenticated)
{
var file = HostContext.VirtualPathProvider.GetFile(httpReq.PathInfo);
if (file == null)
{
return new CustomStaticFileHandler("/404.html");
}
if (httpReq.Headers.GetValues(httpReq.Headers.AllKeys[10])[0] != "XMLHttpRequest")
{
session.ReferrerUrl = httpReq.PathInfo;
return new RedirectHttpHandler
{
AbsoluteUrl = "/Login.html",
};
}
return new CustomResponseHandler((request, response) => HttpError.Unauthorized("User is unauthorized"));
}
}
}