I'm just starting out with C# and ASP.NET and have the following questions. I am working with code adapted from a couple different tutorials playing with Northwind and have gotten this far. The list of acceptable categories is currently hard coded in a string but I would like to look up the CategoryName in the database to verify that it exists.
Obviously the purpose of this is to ensure that users don't just type:
www.domain.com/Categories/AnyUrlWillWork and return a valid page.Also does anyone have an tips of how they are dealing with capitalization issues since the routing is case sensitive? For example Categories/beverages should forward to Categories/Beverages ?
Thanks in advance for any assistance, and glad to be joining 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
"~/Sh开发者_如何转开发owProductsInCategory.aspx", // Physical file
true,
new RouteValueDictionary
{{"CategoryName", "Beverages"}}, //Sets default value if none is provided in URL
new RouteValueDictionary
{{"CategoryName", new EchoConstraint()}}
);
Is this MVC? If so, why not route to a function, which will check the category name against your data store and redirect to an error page if such category doesn't exist?
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();
}
A WebForms solution would be:
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)}}
);
Where you pass an object of class implementing IRepository with your data access logic (using NHibernate, EntityFramework or your own DAL implementation). You need to return a bool value, and this is what I did.
精彩评论