How to redirect with HttpContext - asp.net

My questions are:
So I need to create a custom class / HttpHandler and throw this code in it? Or can I place this somewhere else like in the global.asax?
How do I check for the Host (so check for www.mydomain.com) incoming so I know when to redirect?
Code:
if ("comes from certain domain")
{
context.Response.Status = "301 Moved Permanently";
context.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
}

Paste this into a new .cs file in your App_Code folder:
using System;
using System.Web;
public class TestModule : IHttpModule
{
public void Init(HttpApplication context) {
context.BeginRequest += new EventHandler(context_BeginRequest);
}
void context_BeginRequest(object sender, EventArgs e) {
HttpApplication app = (HttpApplication)sender;
if (app.Request.Url.Host == "example.com") {
app.Response.Status = "301 Moved Permanently";
app.Response.AddHeader("Location", "http://www.testdomain.com/Some.aspx");
}
}
public void Dispose() {
}
}
Then add this to your web.config in system.web:
<httpModules>
<add type="TestModule" name="TestModule" />
</httpModules>

You should be able to place it in the Global.asax, in the Application_BeginRequest event.
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
string host = context.Request.Url.Host;
if (host == "www.mydomain.com")
{
context.Response.Status = "301 Moved Permanently";
context.Response.AddHeader("Location",
"http://www.testdomain.com/Some.aspx");
}
}

I avoid putting anything unnecessary in global.asax as it tends to get cluttered. Instead, create an HttpModule, add an event handler
public void Init(System.Web.HttpApplication app)
{
app.BeginRequest += new System.EventHandler(Rewrite_BeginRequest);
}
and, in the beginRequest method,
public void Rewrite_BeginRequest(object sender, System.EventArgs args)
{
HttpApplication app = (HttpApplication)sender;
/// all request properties now available through app.Context.Request object
}

Related

HTTP module re-writing the URL with some encryption

I am writing one class with the help of HTTPModule to check userIdentity in session before he access any page.If the variable in the session is null or empty i am redirecting the user in session expired page.
Code in Class:
public class SessionUserValidation : IHttpModule
{
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.PreRequestHandlerExecute += new
EventHandler(application_PreRequestHandlerExecute);
}
private void application_PreRequestHandlerExecute(object sender, EventArgs e)
{
HttpApplication application = (HttpApplication)sender;
IHttpHandler handler = application.Context.Handler;
Page reqPage = handler as Page;
if (reqPage != null)
{
reqPage.PreInit += new EventHandler(CustomModule_Init);
}
}
private void CustomModule_Init(object sender, EventArgs e)
{
Page Page = sender as Page;
if (!Page.Request.Url.ToString().Contains("mySessionExpired.aspx") &&
!Page.Request.Url.ToString().Contains("myLogin.aspx"))
{
if (HttpContext.Current.Session["encryptedUserId"] == null)
{
HttpContext.Current.Response.Redirect("../Modulenames/mySessionExpired.aspx", false);
}
}
}
}
everything is working fine , only issue is that its adding some kind of encryption in URL for which my Breadcrumbs are not working in the page. The url transforms like :
://thewebsite/Project/(S(jnd4o5ljdgs0vq1zd4niby4a))/Pages/mySessionExpired.aspx
no idea why this fragment of text has been added ... please help
--Attu

Detect ASP.NET Session Timeout - ASP.NET_SessionId method not working

I'm trying to detect Asp.NET Session Timeout to redirect user to a timeout page; i've checked various methods, most of them similar to
http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.2
(if Session.IsNewSession and ASP.NET_SessionId cookie exists, then is a timeout)
The problem is that the "ASP.NET_SessionId" cookie is always present for me, even if i just started debugging, thus giving me always a false timeout flag when starting the web site for the first time.
UPDATE:
For testing, i've just created an Empty Asp.NET Web Application with following codes:
BasePage.cs
using System;
using System.Web.UI;
namespace TestApp.classes
{
public class BasePage : Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
if (Context.Session != null)
{
if (Session.IsNewSession)
{
string szCookieHeader = Request.Headers["Cookie"];
if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
{
Response.Redirect("sessionTimeout.htm");
}
}
}
}
}
}
Global.asax
using System;
namespace TestApp
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
var a = "";
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
var b = "";
}
protected void Application_End(object sender, EventArgs e)
{
}
}
}
WebForm1.aspx
using System;
using TestApp.classes;
namespace TestApp
{
public partial class WebForm1 : BasePage
{
protected void Page_Load(object sender, EventArgs e)
{
}
}
}
Web.config
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<sessionState timeout="1"></sessionState>
</system.web>
</configuration>
Then Hit F5, and i will be redirected to sessionTimeout.htm. Why?
You don't have to use cookie when you develop your website. There are other ways to store data, e.g. you can store the data specific to a user in database
Note that "Cookieless = false" attrubute of SessionState element in web.config which means the sessionID of the current session will be saved in the client machine as a cookie
<sessionState cookieless="true" />
Default settings for ASP.NET session state are defined in the machine.config file and can be overridden in the web.config file in the application's root folder. By ensuring that the above line appears in the root web.config file, you enable cookieless sessions
Refer http://msdn.microsoft.com/en-us/library/aa479314.aspx
So check only for Session.IsNewSession and disable cookie

asp.net - global.asax in asp.net 2.0 app

I created a global.asax file for an asp.net application. I run some code in the session_start method. The code does not get executed. Is there some type of procedure for using a global.asax file in asp.net 2.0?
I have the asax file itself and also a codebehind file.
Thank you!
Edit:
asax file:
<%# Application Codebehind="Global.asax.cs" Inherits="GrowUp.Global" %>
The code behind file:
using System;
using System.Collections;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
namespace Ligdol
{
/// <summary>
/// Summary description for Global.
/// </summary>
public class Global : System.Web.HttpApplication
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
public Global()
{
InitializeComponent();
}
protected void Application_Start(Object sender, EventArgs e)
{
Application["HostName"] = System.Configuration.ConfigurationSettings.AppSettings["HostName"];
Application["counter"] = 1;
}
protected void Session_Start(Object sender, EventArgs e)
{
// Get the count from the application variable
int counter = int.Parse(Application["counter"].ToString());
//Check if a cookie exists.
if(HttpContext.Current.Request.Cookies["ligdolVersion"] != null)
{
//If a cookie exists, we need to redirect the user to the respective site.
if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "new")
{
Response.StatusCode = 302;
Response.Status = "Moved temporarily";
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else if(HttpContext.Current.Request.Cookies["ligdolVersion"].ToString() == "old")
{
return;
}
}
else if (counter == 40)
{
// If a cookie does not already exist,
//we need to check if the user is to be allowed to continue to the old site
//or be redirected to the new site.
//Note in a file that a user was redirected, so we can get an estimate of how many are being redirected.
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to new site.");
tw.Close();
// Reset counter.
Application["counter"] = 1;
//write cookie made to expire in 30 days, by then the experiment will be over (we hope!).
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "new";
Response.Cookies.Add(cookie);
Response.Redirect("http://beta.ligdol.co.il");
return;
}
else
{
System.IO.TextWriter tw = new System.IO.StreamWriter(#"redirect.log");
tw.WriteLine("Redirected to old site.");
tw.Close();
HttpCookie cookie = new HttpCookie("ligdolVersion");
DateTime dtNow = DateTime.Now;
TimeSpan tsSpan = new TimeSpan(30, 0, 0, 0, 0);
cookie.Expires = dtNow + tsSpan;
cookie.Value = "old";
Response.Cookies.Add(cookie);
return;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
}
protected void Application_EndRequest(Object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
protected void Application_Error(Object sender, EventArgs e)
{
}
protected void Session_End(Object sender, EventArgs e)
{
}
protected void Application_End(Object sender, EventArgs e)
{
}
#region Web Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
}
#endregion
}
}
The issue was the codebehind file. Once I put the code inline inside the asax file, it worked. This might be the only solution for old website projects.

load different css for site localization

I need to load different css file depending on the language that the user selects. I need to do this only in my master page.
If you are using the built-in themes and globalization support you could use a httpModule: (untested)
public class PageModule : IHttpModule
{
public void Dispose()
{
}
public void Init(System.Web.HttpApplication context)
{
context.PreRequestHandlerExecute += Application_PreRequestHandlerExecute;
}
public void Application_PreRequestHandlerExecute(object sender, EventArgs e)
{
//Adds a handler that executes on every page request
HttpApplication application = default(HttpApplication);
application = (HttpApplication)sender;
Page page = application.Context.CurrentHandler as Page;
if ((page != null))
page.PreInit += Page_PreInit;
}
public void Page_PreInit(object sender, EventArgs e)
{
//If current context has no session then abort
if (HttpContext.Current.Session == null)
return;
//Get current page context
Page page = (Page)sender;
switch (page.Culture) {
case "en-US":
page.Theme = "en-USTheme";
break;
case "fr-FR":
page.Theme = "fr-FRTheme";
break;
default:
page.Theme = "DefaultTheme";
break;
}
}
}
you could write the selected language in a cookie. Then in you master page inspect the value saved in the cookie and assign the correct stylesheet.

Is it possible to execute a function at IIS for authentication before hits URLs?

Our applications are hosted at IIS as below hierarchy:
MainAppn1
---subAppn1
---subAppn2
---subAppn3
Is it possible to execute a function automatically at IIS to do authentication commonly for all sub applications whenever user hits url (for eg. http://server1/MainAppn1/subAppn1.aspx. Best answers would be greatly appreciated!.
You could implement Custom HTTP Module.
namespace AspNetWebForm
{
public class CustomHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
application.BeginRequest += Application_BeginRequest;
application.AuthenticateRequest += Application_AuthenticateRequest;
application.AuthorizeRequest += Application_AuthorizeRequest;
}
private void Application_BeginRequest(object sender, EventArgs e)
{
}
private void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
private void Application_AuthorizeRequest(object sender, EventArgs e)
{
}
public void Dispose()
{
}
}
}
web.config
Registering the HTTP Module in IIS 7.0 Integrated Mode.
<configuration>
<system.webServer>
<modules>
<add name="CustomHttpModule" type="AspNetWebForm.CustomHttpModule"/>
</modules>
</system.webServer>
</configuration>

Resources