Search code examples
webformsvs-web-application-project

Getting the url of an aspx page using the page type


I'm using a web application project.

I have a folder in my web root called Users and in the folder I have a page called UserList.aspx

What I want to be able to do is type in Response.Redirect(Users.UserList.URL)

What I reckon I can probably do is create a class that extends Page and add a static property called URL that calls MethodInfo.GetCurrentMethod().ReflectedType (I think this works haven't tested) and then have that convert Users.UserList -> ~/Users/UserList.aspx

The problems with this method that I know of are one I need to go through every page and make it extend the base class and it doesn't work with any pages that contain a '-' character.

The advantages are that if pages are moved around then there aren't any broken links (Resharper gives out when there is a Page with the wrong namespace).

Also then every individual page that takes query string params could have a static method so that if I want to add/remove params I can see what uses those params etc. Also if I want to call that page I don't have to check the name of the params e.g. UserId userId, Id or id. So that would look something like Users.ViewUser.GetUrl(1) -> ~/Users/ViewUser.aspx?UserId=1

So the question is: Is there a better way of doing this? Or is this a bad idea in principal?


Solution

  • The MethodInfo.GetCurrentMethod().ReflectedType doesn't work so I came up with another method of doing this using generics.

    Instead of Users.ViewUser.GetUrl() or Users.ViewUser.URL it's GetUrl() For a page with parameters it's still Users.ViewUser.GetUrl(1), it isn't ideal because they should both have the same way of being called but better than strings I guess.

    Going to leave the question open for a while just in case.

    edidt: I think I will actually just create another method called GetUrl(String getQuery) because if I have two parameters that are of the same type it doesn't work very well.

    further edit: I found out how to do exactly what I want to do. created a class called BasePage:Page where T : Page on that are the static methods redirect and geturl each page inherits from the base page as follows: MyPage:BasePage Any page can redirect to that page by using the command MyPage.Redirect();