ASP.NET路由 - 使用数据库查找路由约束

时间:2010-08-24 23:35:51

标签: c# asp.net database routing case-sensitive

我刚刚开始使用C#和ASP.NET,并提出以下问题。我正在使用改编自Northwind的几个不同教程的代码,并且已经做到了这一点。可接受类别列表目前在字符串中进行了硬编码,但我想在数据库中查找CategoryName以验证它是否存在。

显然,这样做的目的是确保用户不只是输入:
www.domain.com/Categories/AnyUrlWillWork 并返回有效页面。

也有人知道他们如何处理大写问题,因为路由区分大小写?例如类别/饮料应该转发到类别/饮料

提前感谢您的帮助,并很高兴加入Stack Overflow。

//Complex contraint class
public class EchoConstraint : IRouteConstraint
{
    public readonly string[] ValidMessages = { "Beverages", "Produce", "Confections", "Seafood" };

    public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
    {
        string message = values["CategoryName"] as string;
        return ValidMessages.Contains(message);
    }
}


//Routes
RouteTable.Routes.MapPageRoute(
                        "Category Route",                       // Route name
                        "Categories/{CategoryName}",            // Url pattern
                        "~/ShowProductsInCategory.aspx",        // Physical file
                        true,
                        new RouteValueDictionary            
                            {{"CategoryName", "Beverages"}},         //Sets default value if none is provided in URL
                        new RouteValueDictionary 
                            {{"CategoryName", new EchoConstraint()}}
                           );

1 个答案:

答案 0 :(得分:2)

这是MVC吗?如果是这样,为什么不路由到一个函数,它将根据您的数据存储检查类别名称,如果不存在这样的类别,则重定向到错误页面?

public ActionResult Index(string catName)
{
    if (string.IsNullOrEmpty(catName) || !MyCategoriesDataStore.Exists(catName))
        return RedirectToAction("CategoryError");

    // Load category data to be used from View

    return View();
}

WebForms解决方案将是:

    public class EchoConstraint : IRouteConstraint
    {
        private IRepository rep;
        public EchoConstraint(IRepository r) { rep = r; }

        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            return rep.GetCategory(message) == 0;
        }
    }
.
.
.
                        new RouteValueDictionary 
                            {{"CategoryName", new EchoConstraint(myDataAccessRepo)}}
                           );

使用数据访问逻辑传递实现IRepository的类的对象(使用NHibernate,EntityFramework或您自己的DAL实现)。你需要返回一个bool值,这就是我所做的。

相关问题