Redirect URL Using HttpModule Asp.net - asp.net

I have created an HttpModule so that Whenever I type "localhost/blabla.html" in the browser, it will redirect me to www.google.com (this is just an example, it's really to redirect requests coming from mobile phones)
My Questions are :
1) How do I tell IIS(7.0) to redirect each request to the "HttpModule" so that it is independent of the website. I can change the web.config but that's it.
2) Do I need to add the .dll to the GAC? If so, How can I do that?
3) The HttpModule code uses 'log4net' . do I need to add 'log4net' to the GAC as well?
Thanks
P.S. the site is using .net 2.0.

You can use request object in BeginRequest event
public class MyHttpModule : IHttpModule
{
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(this.context_BeginRequest);
}
private void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
HttpContext context = application.Context;
//check here context.Request for using request object
if(context.Request.FilePath.Contains("blahblah.html"))
{
context.Response.Redirect("http://www.google.com");
}
}
}

Related

HttpModule endless redirect

I'm using an HttpModule to try and redirect users to the login page if they're not authenticated, but for some reason it's just endlessly redirecting the page without landing anywhere.
Here's the module:
using System;
using System.Web;
using System.Web.Security;
public class AuthenticationModule : IHttpModule
{
public AuthenticationModule()
{
}
public string ModuleName
{
get
{
return "AuthenticationModule";
}
}
public void Init(HttpApplication app)
{
app.BeginRequest += (new EventHandler(Application_BeginRequest));
}
private void Application_BeginRequest(object source, EventArgs e)
{
HttpApplication app = (HttpApplication)source;
HttpContext context = app.Context;
HttpRequest request = context.Request;
HttpResponse response = context.Response;
if (!request.IsAuthenticated && !request.RawUrl.Contains(FormsAuthentication.LoginUrl))
{
FormsAuthentication.RedirectToLoginPage();
}
}
public void Dispose() { }
}
I don't recall having ever worked with HttpModules before, so I'm not sure what's not working.
How can I fix this?
request.RawUrl is the URL I entered into the browser. Your check request.RawUrl.Contains(FormsAuthentication.LoginUrl) is case sensitive.
Additionally there are no checks for ressources. So each request for images, css files etc. will redirect to login page. You need to check if authentication is required for the ressource being called.
Edit (hit the save button to early)
Additionally I would do it on AuthenticateRequest

how to set Setting Expires and Cache-Control: max-age headers for images only in ASP.NET?

I have a website with files which are static like Jquery library, images and other JS files.
So, I wish to set expiry time for those resources specifically so that those can be easily retrieved from users cache and without caching other static resources
can anybody suggest a way to do that in asp.net 3.5?
Thank You
You should separate this static files in folder and configure it directly on IIS
Here's a example for IIS6:
http://www.websiteoptimization.com/secrets/advanced/9-7-content-expiration-IIS.html
Or via code you can implement an IHttpModule
public class CacheExpiresModule : IHttpModule
{
public void Dispose() { }
public void Init(HttpApplication context)
{
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string url = context.Request.Url.ToString();
if (url.Contains("/Static/"))
{
context.Response.Cache.SetExpires(DateTime.Now.AddYears(30));
context.Response.Cache.SetMaxAge(TimeSpan.FromDays(365));
}
}
}
and configure it on your web.config
You can leverage browser caching setting an expiration data through http headers. There is a brief explanation of this process from Google Developers / Page Speed Insight:
https://developers.google.com/speed/docs/insights/LeverageBrowserCaching

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
?
Have you tried using HTTPContext.Current?
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.

Asp.net global output cache

Last few days I thinkin about output cache in asp.net. In my task I need to implement output cache for the very big project. After hours of searching I did not find any examples.
Most popular way to use output cache is declarative, in this case you need to write something like this on the page which you want to cache.
But if you need to cache whole site you must write this on all pages or master pages on project. It is madness. In this case you cant store all configuration in one place. All page have his own configurations..
Global.asax could help me, but my site contains about 20 web progects and ~20 global.asax files. And i don't want copy same code to each project.
For these reasons, i made decision to create HTTPModule.
In Init method i subscribe to two events :
public void Init(HttpApplication app)
{
app.PreRequestHandlerExecute += new EventHandler(OnApplicationPreRequestHandlerExecute);
app.PostRequestHandlerExecute += new EventHandler(OnPostRequestHandlerExecute);
}
In method "OnPostRequestHandlerExecute" I set up output caching parameters for each new request :
public void OnPostRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
HttpCachePolicy policy = app.Response.Cache;
policy.SetCacheability(HttpCacheability.Server);
policy.SetExpires(app.Context.Timestamp.AddSeconds((double)600));
policy.SetMaxAge(new TimeSpan(0, 0, 600));
policy.SetValidUntilExpires(true);
policy.SetLastModified(app.Context.Timestamp);
policy.VaryByParams.IgnoreParams = true;
}
In "OnApplicationPreRequestHandlerExecute" method I set calback method to cache validation:
public void OnApplicationPreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
app.Context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), app);
}
And last part - callback validation method :
public void Validate(HttpContext context, Object data, ref HttpValidationStatus status)
{
if (context.Request.QueryString["id"] == "5")
{
status = HttpValidationStatus.IgnoreThisRequest;
context.Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), "somecustomdata");
}
else
{
status = HttpValidationStatus.Valid;
}
}
To attach my HttpModule I use programmatically attach method :
[assembly: PreApplicationStartMethod(typeof(OutputCacheModule), "RegisterModule")]
This method works perfectly, but I want to know is there other ways to do this.
Thanks.
Try seeing if IIS caching provides what you need.
http://www.iis.net/configreference/system.webserver/caching

c# HttpModule to handle pseudo sub-domains

I'm new to development with .NET and working on a personal project. My project will allow users to create their own simple mobile site.
I would like to write a HTTP Module that will handle pseudo sub-domains.
I have already setup my DNS wildcard, so sub.domain.com and xxx.domain.com etc. point to the same application. I want to be able to extract sub and ID parts from sub.domain.com/pageID.html URL and load settings of the page from a database server in order to build and render the page to the client.
I can do it with URL rewrite tools like isapirewrite, but I want my application to be independent from OS so that the server doesn't require installation of any 3rd party app.
Is it possible to do it with HTTP handlers?
Can anyone post an example?
You can check the domain at any time. Where to do it dependings on your application's goals. E.g. if you want to serve different pages depending on the domain you could do like this:
public class MyModule : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.BeginRequest += context_BeginRequest;
}
void context_BeginRequest(object sender, EventArgs e)
{
HttpApplication app = sender as HttpApplication;
string host = app.Request.Url.Host;
if(host == "first.domain.com")
{
app.Context.RewritePath("~/First.aspx");
}
}
}

Categories

Resources