【发布时间】:2011-01-07 07:21:49
【问题描述】:
我正在寻找一种最佳实践解决方案,旨在减少在 ASP.NET 应用程序中硬编码的 URL 数量。
例如,当查看产品详细信息屏幕、对这些详细信息执行编辑然后提交更改时,用户将被重定向回产品列表屏幕。而不是编写以下代码:
Response.Redirect("~/products/list.aspx?category=books");
我想有一个合适的解决方案,让我可以做这样的事情:
Pages.GotoProductList("books");
其中Pages 是公共基类的成员。
我只是在这里吐口水,很想听听任何人管理其应用程序重定向的任何其他方式。
编辑
我最终创建了以下解决方案:我已经有一个公共基类,我向其中添加了一个 Pages 枚举(感谢 Mark),每个项目都有一个包含页面 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
}
然后我创建了一些重载方法来处理不同的场景。我使用反射通过它的Description 属性获取页面的 URL,并将查询字符串参数作为匿名类型传递(也使用反射将每个属性添加为查询字符串参数):
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"});
评论?
【问题讨论】:
标签: asp.net url response.redirect