I am looking for a best practice solution whose goal is to reduce the number of URLs hardcoded in an ASP.NET application.
For example, when viewing a product details screen, editing that information, and then submitting the changes, the user is redirected back to the product list screen. Instead of coding:
Response.Redirect("~/products/list.aspx?category=books");
I would like to have a solution allowing me to do something like this:
Pages.GotoProductList("books");
where Pagesis a member of a common base class.
I just stumbled here and would like to hear any other way that someone controlled the redirection of their applications.
EDIT
In the end, I created the following solution: I already had a common base class to which I added the Pages enumeration (thanks to Mark), and each element has an attribute System.ComponentModel.DescriptionAttributecontaining the page URL:
public enum Pages
{
[Description("~/secure/default.aspx")]
Landing,
[Description("~/secure/modelling/default.aspx")]
ModellingHome,
[Description("~/secure/reports/default.aspx")]
ReportsHome,
[Description("~/error.aspx")]
Error
}
Then I created several overloaded methods to handle various scripts. I used reflection to get the page URL through the attribute Description, and I pass the query string parameters as an anonymous type (also using reflection to add each property as a query string parameter):
private string GetEnumDescription(Enum value)
{
Type type = value.GetType();
string name = Enum.GetName(type, value);
if (name != null)
{
FieldInfo field = type.GetField(name);
if (field != null)
{
DescriptionAttribute attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
if (attr != null)
return attr.Description;
}
}
return null;
}
protected string GetPageUrl(Enums.Pages target, object variables)
{
var sb = new StringBuilder();
sb.Append(UrlHelper.ResolveUrl(Helper.GetEnumDescription(target)));
if (variables != null)
{
sb.Append("?");
var properties = (variables.GetType()).GetProperties();
foreach (var property in properties)
sb.Append(string.Format("{0}={1}&", property.Name, property.GetValue(variables, null)));
}
return sb.ToString();
}
protected void GotoPage(Enums.Pages target, object variables, bool useTransfer)
{
if(useTransfer)
HttpContext.Current.Server.Transfer(GetPageUrl(target, variables));
else
HttpContext.Current.Response.Redirect(GetPageUrl(target, variables));
}
A typical call would look like this:
GotoPage(Enums.Pages.Landing, new {id = 12, category = "books"});
Comments?