我需要使用 HttpModule 编写一个自定义的“UrlRewriter”,在“重写”的那一刻,我需要访问 Session 并遵循了另一个 SO 线程的建议:
Can I access session state from an HTTPModule?
一切正常,除了 RewritePath/Redirect 部分。我没有任何异常(exception),但浏览器需要很长时间才能加载。这真的是构建这样的 urlrewriter 的最佳方式吗?
using System;
using System.Web;
using System.Web.SessionState;
using System.Diagnostics;
namespace MyCompany.Campaigns
{
public class CampaignRewriteModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.PostAcquireRequestState += new EventHandler(Application_PostAcquireRequestState);
application.PostMapRequestHandler += new EventHandler(Application_PostMapRequestHandler);
}
void Application_PostMapRequestHandler(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
if (app.Context.Handler is IReadOnlySessionState || app.Context.Handler is IRequiresSessionState)
{
return;
}
app.Context.Handler = new MyHttpHandler(app.Context.Handler);
}
void Application_PostAcquireRequestState(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
MyHttpHandler resourceHttpHandler = HttpContext.Current.Handler as MyHttpHandler;
if (resourceHttpHandler != null)
{
HttpContext.Current.Handler = resourceHttpHandler.OriginalHandler;
}
Debug.Assert(app.Session != null);
string path = HttpUtils.Path();
if (!CampaignCodeMethods.IsValidCampaignCode(path)) return;
string domain = HttpUtils.Domain();
CampaignCode code = CampaignManager.RegisterCode(path, domain.Equals(Config.Instance.Domain.ToLower()) ? null : domain);
if (code != null)
{
//app.Context.RewritePath(code.CampaignCodePath.Path, false);
app.Context.Response.Redirect(code.CampaignCodePath.Path, true);
}
}
public void Dispose() { }
public class MyHttpHandler : IHttpHandler, IRequiresSessionState
{
internal readonly IHttpHandler OriginalHandler;
public MyHttpHandler(IHttpHandler originalHandler)
{
OriginalHandler = originalHandler;
}
public void ProcessRequest(HttpContext context)
{
throw new InvalidOperationException("MyHttpHandler cannot process requests.");
}
public bool IsReusable
{
get { return false; }
}
}
}
}
最佳答案
我想我知道它是什么。您的模块在所有请求上执行并分配一个处理程序,除非存在有效的事件代码(发生重写/重定向),否则该处理程序会引发错误。
但是因为这不仅仅是针对您的“处理程序事件代码”url,它会导致抛出错误,从而导致您被重定向到错误页面,该页面正在被分配处理程序的模块捕获正在抛出一个错误,这是重定向......我想你知道我要去哪里;)
否则我会尝试一些事情:
关于c# - UrlRewriter+HttpModule+Session 问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/506431/