Custom HTTP handler for URL rewriting + session and application variable

2.4k Views Asked by At

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 ?

2

There are 2 best solutions below

1
On BEST ANSWER

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.

2
On

Have you tried using HTTPContext.Current?