Click here to Skip to main content
15,887,683 members
Articles / Web Development / ASP.NET
Tip/Trick

Strong Typed Response.Redirect

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
4 Apr 2011CPOL1 min read 17.3K   1   6
Strong Typed Response.Redirect
Few days ago, I was looking for a good way to replace all the ugly Response.Redirect(“page.apx”) with a strong typed version in all the web site. First thing I did (as a good developer should always do) was I was looking on internet for a best practice/good way to achieve this behaviour but I could not find a good solution: most of the posts I found were talking about creating kind of base class… etc. but as soon as I read “BaseClass”, I stopped reading because it meant I had to refactor all the code to use the new base class. Anyway let us go straight to the point.

Using the extensions method I have done, you can now do something like the below:

Response.Redirect<MyPage>();


The good point is it works even if the page has got a different name from the base class (code behind) even if it is not very common. What I’m saying is the extension method will work even in the case below.

Let's say I want to redirect to MyNicePage.aspx.

Suppose the page code behind class has got a different name(it should be Class MyNicePage{}).

partial class MyPage{...}


I will able to do:

Response.Redirect<MyPage>();


and it will redirect to MyNicePage.aspx.

Let’s have a look at the code:

First of all, you need to create an extension method for the Page class which returns the page name by page Type:

using System;
using System.Web.UI;
using System.Linq;
public static class PageReferenceExtensions
{
    public static string GetPageName(this Page page)
    {
        var pageClassType=GetPageClassType(page);
        var pageName=GetPageNameByPageClassType(pageClassType);
        return pageName;
    }

    private static Type GetPageClassType(Page page)
    {
        //don't convert the below using a Linq expression!
        //Linq is a lot slower than the classic foreach
        var types = page.GetType().Assembly.GetTypes();
        foreach (var type in types)
        {
            if (type.IsSubclassOf(page.GetType()))
            {
                return type;
            }
        }
        return null;
    }

    private static string GetPageNameByPageClassType(Type t)
    {
        //the below can be improved
        var pageNameToListString= t.Name.Split('_').ToList();
        var pageExtension = pageNameToListString.Last();
        pageNameToListString.Remove(pageExtension);
        var pageName = pageNameToListString[pageNameToListString.Count - 1];
        pageNameToListString.Remove(pageName);
        var pagePath = string.Join("/", pageNameToListString);
        return pagePath + "/" + pageName + "." + pageExtension;
    }
}


Then, you need to create the extension method for HttpResponse class as below:

using System.Web;
   using System.Web.UI;

   public static class HttpResponseExtension
   {
      public static void Redirect<T>(this HttpResponse response) where T : Page, new()
      {
          string pageName = GetPageName<T>();
          response.Redirect("~/" + pageName);
      }

      private static string GetPageName<T>() where T : Page, new()
       {
           var page = new T();
           return page.GetPageName();
       }

       public static void Redirect<T>(this HttpResponse response, string queryString) where T : Page, new()
       {
           string pageName = GetPageName<T>();
           response.Redirect("~/" + pageName + queryString);
       }
   }


As you can see, there is also an overload that takes the query string.

You could use this method to create extension methods for the “Server.Transfer” which performance wise is faster.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect PeluSoft Limited
United Kingdom United Kingdom
I have been fascinated by software development since I was 10 years old. I'm proud of learned the first programming language with an Olivetti PC 128S based on Microsoft BASIC. I'm a Software Architect/Senior Developer with a strong background of all the developing Microsoft's technologies.

Comments and Discussions

 
QuestionWhy? Pin
Jason Vetter5-Apr-11 7:44
Jason Vetter5-Apr-11 7:44 
AnswerRe: Why? Pin
Massimiliano Peluso "WeDev Limited"5-Apr-11 7:57
Massimiliano Peluso "WeDev Limited"5-Apr-11 7:57 
GeneralRe: Why? Pin
EngleA6-Apr-11 3:40
EngleA6-Apr-11 3:40 
GeneralRe: Why? Pin
Massimiliano Peluso "WeDev Limited"6-Apr-11 3:53
Massimiliano Peluso "WeDev Limited"6-Apr-11 3:53 
GeneralRe: Why? Pin
RonDsz27-Apr-11 11:02
RonDsz27-Apr-11 11:02 
GeneralRe: Why? Pin
Massimiliano Peluso "WeDev Limited"27-Apr-11 21:58
Massimiliano Peluso "WeDev Limited"27-Apr-11 21:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.