我在一个房地产网站上工作并使用 URL 路由,这样我的客户就可以让他们的特色特性在 URL 中显示他们的地址:www.realestatewebsite.com/featured/123-Fake-St
但是,我是 URL 路由的新手,我认为我走了一条糟糕的捷径。我本来想使用我的数据库的主键来访问属性 (propID),但不想将它传递到 URL,所以改为使用地址来获取 propID 并从那里使用它。但是,如果我尝试将 Page.RouteData.Values["address"] 分配给一个字符串,而 URL 中没有地址,则会引发异常。因此我有一个 try/catch 语句来处理它。不过,这对我来说似乎是不好的做法。如果有人可以告诉我这样做是否可以接受,或者如果有更好的解决方案,请告诉我。
这是 Global.asax:
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
RegisterRoutes(RouteTable.Routes);
}
public static void RegisterRoutes(RouteCollection routes)
{
routes.MapPageRoute("", "Featured/{address}", "~/Featured/Default.aspx");
}
这是来自 www.website/com/Featured/Default.aspx 的方法:
protected int getPropID()
{
string address;
int propID = -1; //If the method returns -1 the page just lists all featured properties
try
{
address = Page.RouteData.Values["address"].ToString();
}
catch (Exception ex)
{
return propID;
}
if (address != null)
{
string strSQL = "SELECT propID FROM tblFeatured WHERE address = '" + address + "'";
DataTable dt = da.FillDataTable(strSQL);
if (dt.Rows.Count > 0)
propID = Convert.ToInt32(dt.Rows[0]["propID"]);
return propID;
}
else
return propID;
}
最佳答案
您正在以典型方式处理此问题。 Scott Gu's URL Routing with ASP.NET 4显示与您正在使用的完全相同的模式。
- 设置路线
- 确保 token 位于某个 URL 上
- 在目标 .aspx 页面的页面加载中,获取 token ,查询数据库。
- 根据需要为该 token 显示您的标记
如果您正在寻找建议:
- 每个属性都应该在您的数据库中预先提取一个“slug”或 token 。只是要查询的另一个属性,而不是数字标识符。 DataTable 的帮助不大。
- 将您的 token 保留为街道地址(如果您的客户不介意,可以包括城市以用于 SEO juice)
- 使用该 token 在数据库中查找房屋/属性(property)记录。此时忘记数字 ID。选择 token 匹配的属性,并将其写入页面。性能差异为零。
string propertyToken = Page.RouteData.Values["address"].ToString();
Property p = PropertyDatabase.GetSingleByToken(propertyToken);
if(p!=null)
{
WritePropertyToPage(p);
}
else
{
//write to page that token wasn't found/misspelled/expired/etc.
}
关于c# - .aspx 中的 URL 路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7069515/