Guilherme David da Costa
Guilherme David da Costa

Reputation: 2368

Redirect route at global.asax.cs

Is there a way for me to make everyone that access localhost/subscribe to be redirected to localhost/subscribe.aspx by using a rule inside global.asax.cs or should I redirect from action?

Upvotes: 3

Views: 13815

Answers (3)

Mikey G
Mikey G

Reputation: 3491

If you are redirecting a virtual url to a physical file, it's pretty easy to do this in the Global.asax:

protected void Application_Start(object sender, EventArgs e)
{
     RegisterRoutes(RouteTable.Routes);
     RouteTable.Routes.MapPageRoute("Key", "Home", "~/Public/Pages/Default.aspx");
}

In this case,

http://www.example.com/Home

redirects to

http://www.example.com/Public/Pages/Default.aspx

Just an FYI, doing this doesn't redirect on the client, it redirects on the server, meaning that the server doesn't return a 302 with the new address, it simply sends back the content you're directing it to.

This is also nifty for adding variables, like this:

routes.MapPageRoute("MainPublic3", "Public/Pages/{PAGE}/{CHILD}", "~/Public/Pages/Pages.aspx");

These can then be accessed in the code behind like this:

string page = Page.RouteData.Values["PAGE"];
string child = Page.RouteData.Values["CHILD"];

We use this for everything where I work, of course we are switching to MVC :)

Upvotes: 2

Vitaliy
Vitaliy

Reputation: 2804

Following code should work for you:

protected void Application_BeginRequest(Object sender, EventArgs e)
{
    if (Request.RawUrl.ToLower().EndsWith("subscribe")) 
    {
        Response.Redirect("subscribe.aspx");
    }
}

Or inside Application_PreRequestHandlerExecute method if you going to use also Session for verifications

Upvotes: 12

Dallas
Dallas

Reputation: 2227

Phil Haack has an example of redirecting using routes

However for one url the easiest solution is probably to redirect from the action.

Upvotes: 3

Related Questions