Search code examples
asp.neturl-rewritinghttpmodulevanity-url

Custom HTTP handler for URL rewriting + session and application variable


Currently my product page URL is like

http://www.localhost:80/products/default.aspx?code=productCode

I want to access product page with

http://www.localhost:80/productCode

I have used HTTP module for this.

public class UrlRewritingModule : IHttpModule

{

        public void Dispose()
        {

        }
        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);

           context.AuthorizeRequest += new EventHandler(context_AuthorizeRequest);


        }  
        void context_AuthorizeRequest(object sender, EventArgs e)
        {
             HttpContext context = ((HttpApplication)sender).Context;
            if (some condition)
            {
               context.RewritePath(url);
             }
        }
        void context_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            //We set back the original url on browser
            HttpContext context = ((HttpApplication)sender).Context;

            if (context.Items["originalUrl"] != null)
            {
                context.RewritePath((string)context.Items["originalUrl"]);
            }
        }
}

I have register it in web.config and it is working fine. But when I deploy it in IIS that session and application variables are not throwing null referent Exceptions.

Can anyone help me?

Edit: Do it require extra code to access session/ Application variable for rewritten URLs ?


Solution

  • I was able to solve issue (accessing session and application variables in subsequent pages rewritten by custom handler) by adding runAllManagedModulesForAllRequests="true" attribute in modules in web.config.