ASP NET MVC 2 - MVC Front Loading - Part 2 1/26/2011 All ASP NET MVC 2 posts
In my last Front Loading post I detailed how you could front-load data in your OnAuthorization method (you could use other methods, but this one seems appropriate). Further optimization led me to create a SetContext utility method that would do most of the repetitive functionality and allow me to quickly and clearly pull route values from the context and load that data generically.
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
CurrentItem = SetContext<string, Item>(filterContext,
"item", BOFactory.ItemBO.Get, true);
CurrentThing = SetContext<int, Thing>(filterContext,
"thing", BOFactory.ThingBO.Get, true);
}
The SetContext method takes the current context, a key to look up in the RouteValues collection, a method to point to that actually loads that data based on TKey, and then whether or not to redirect if the object was not found.
TModel SetContext<TKey, TModel>(AuthorizationContext context,
string key, Func<TKey, TModel> func, bool redirectOnNull)
where TModel : class
{
string routeValue = HttpUtility.UrlDecode(
Convert.ToString(context.RouteData.Values[key]));
if (!string.IsNullOrEmpty(routeValue.ToString()))
{
TKey k = default(TKey);
if (typeof(TKey) == typeof(int))
{
int i;
if (int.TryParse(routeValue, out i))
{
k = (TKey)(object)i;
}
}
else
{
k = (TKey)(object)routeValue;
}
if (!k.Equals(default(TKey)))
{
TModel result = func(k);
if (result == null && redirectOnNull)
{
HandleContextError<TKey, TModel>(context, "{0} '{1}' not found",
typeof(TModel).Name, k);
}
return result;
}
else if (!string.IsNullOrEmpty(routeValue))
{
HandleContextError<TKey, TModel>(context, "{0} '{1}' not found",
typeof(TModel).Name, k);
}
}
return null;
}