我有一个HttpHandler,我正试图在我的网站的某个目录上放置一点安全层,但它表现得很奇怪。
我已经在我的Web上注册了它。配置: 不再有效,因为我在IIS 7.5中
<httpHandlers>
<add verb="*" path="/courses/*" type="CoursesAuthenticationHandler" />
我无法判断它是否实际被调用,因为无论代码如何,它似乎总是无所作为。另一方面,如果代码中有任何错误,它会显示错误页面,直到我纠正错误。
这是处理程序本身:
using System;
using System.Web;
public class CoursesAuthenticationHandler : IHttpHandler
{
public bool IsReusable
{
get { return true; }
}
public void ProcessRequest(HttpContext context)
{
if (!context.Request.IsAuthenticated)
context.Response.Redirect("/");
}
}
所以......就是这样。处理程序正在编译时进行注册和分析,但实际上并没有按预期执行。
编辑:我意识到我正在使用IIS 7.5,这确实对此实现产生了影响。
对于IIS 7,这是我使用的Web.Config注册:
<handlers accessPolicy="Read, Execute, Script">
<add name="CoursesAuthenticationHandler"
verb="*"
path="/courses/*"
type="CoursesAuthenticationHandler"
resourceType="Unspecified" />
编辑2:进度!未登录时,对/courses/
目录的请求将重定向到登录页面。但是,对/courses/
目录的已验证请求将返回空页...
编辑3:根据@ PatrickHofman的建议,我已转而使用HttpModule
。
Web.Config注册:
<modules>
<add name="CourseAuthenticationModule" type="CourseAuthenticationModule" />
代码:
using System;
using System.Web;
public class CourseAuthenticationModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(BeginRequest);
}
public void BeginRequest(Object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (request.Path.ToLower().StartsWith("/courses/") && !request.IsAuthenticated)
{
response.Redirect("/");
}
}
}
现在问题是!request.IsAuthenticated
总是为false。如果我已登录并导航到/courses/
目录,我将被重定向到主页。
这是什么交易?
答案 0 :(得分:1)
我认为最后一个问题在于HttpHander
处理东西。这是请求的终点。
由于您未向请求添加任何内容,因此响应将以空白结束。
您在寻找HttpModule
吗?它们可以叠放。
作为仅在需要文件时的可能解决方案:通过读取和写入响应来读取请求中的文件或使用TransmitFile
。对于ASP.NET页面,您需要模块。