我正在尋找一種最佳實踐解決方案,旨在減少在ASP.NET應用程序中硬編碼的URL數量。ASP.NET - 避免硬編碼路徑
例如,查看產品詳細信息屏幕,對這些詳細信息執行編輯,然後提交更改時,用戶將重定向回產品列表屏幕。相反,編碼如下:
Response.Redirect("~/products/list.aspx?category=books");
我想有一個適當的解決方案,可以讓我做這樣的事情:
Pages.GotoProductList("books");
其中Pages
是公共基類中的一員。
我只是吐口水在這裏,並希望聽到任何人都管理其應用程序重定向的其他方式。
編輯
我結束了創建以下解決方案:我已經有一個共同的基類,而我添加了一個頁面枚舉(感謝馬克),與具有含網頁的URL一個System.ComponentModel.DescriptionAttribute
屬性的每個項目:
public enum Pages
{
[Description("~/secure/default.aspx")]
Landing,
[Description("~/secure/modelling/default.aspx")]
ModellingHome,
[Description("~/secure/reports/default.aspx")]
ReportsHome,
[Description("~/error.aspx")]
Error
}
然後,我創建了一些重載的方法來處理不同的情況。我使用反射來獲取頁面的URL通過它的Description
屬性,和我通過查詢字符串參數作爲一個匿名類型(也使用反射來每個屬性添加作爲查詢字符串參數):
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));
}
一典型的呼叫將如下所示:
GotoPage(Enums.Pages.Landing, new {id = 12, category = "books"});
評論?
我最終做了類似的事情(參見上面的編輯),並將其標記爲已接受,因爲我使用了頁面枚舉的想法。謝謝馬克。 – staterium 2010-01-23 15:28:38