我正在寻找一种最佳实践解决方案,旨在减少在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