How to limit HttpModule with ONLY ONE call per request?

非 Y 不嫁゛ 提交于 2019-12-04 19:06:47

If Init() hasn't finished before the second request comes along then your HttpModule isn't ready yet. If you have code in your Init() method that should run only once then you can set a flag (bool initialised) and use a lock to prevent the code from being run by more than one thread, e.g.:

private static bool initialised;
private static object lockObject = new object();

public void Init(HttpApplication app)
{
    lock(lockObject)
    {
         if(!initialised)
         {
           app.BeginRequest += ProcessRequest;
           //... other code here
           initialised = true;
         }
    }
}

Update: As this article explains, ASP.NET may create more than one instance of your HttpModule, so Init() can be called more than once. This is by design. Therefore you must fashion the module so that code that should run only once is run only once - by applying locking, like above.

I'd say the obvious answer is that your handler is handling more than one request, likely for stylesheets or images.

Add the following into your ProcessRequest event handler and add a watch to context.Request.PhysicalPath to confirm this.

HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;

string filename = Path.GetFileName(context.Request.PhysicalPath);

If you don't want your handler to run for requests for images etc, all you need to do is check for the path ending ".aspx" or something similar.

When you execute Init() twice, the BeginRequest event will call twice your processing because it has two event handlers in it. The += operator adds the new event handler in a list, it doesn't replace the old handler(s).

Øyvind has a correct solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!