views:

31

answers:

1

I have been struggling with this for the past few hours. All I'm trying to do is pick action parameters from the current route like this. This method resides inside a simple static helper class.

    public static string GetStateName(ActionExecutingContext filterContext)
    {
        var stateParam = filterContext.ActionParameters.Where(p => p.Key == RouteConst.StateName).FirstOrDefault();
        return !string.IsNullOrEmpty(stateParam.Key) ? stateParam.Value.ToType<string>() : string.Empty;
    }

However, I do not like the idea of passing in the context every time I have to call this method. Is there a way to access the current executing context just like HttpContext.Current?

Update: Using Necros' suggestion, this is what I ended up doing.

public static class ActionExtensions {

    public static string GetMarketName(this ActionExecutingContext filterContext)
    {return GetActionParamValue(filterContext, RouteConst.MarketName).ToType<string>();}

    public static string GetStateName(this ActionExecutingContext filterContext)
    {return GetActionParamValue(filterContext, RouteConst.StateName).ToType<string>();}

    private static string GetActionParamValue(ActionExecutingContext filterContext, string actionParamName)
    {
        var actionParam = filterContext.ActionParameters.Where(p => p.Key == actionParamName).FirstOrDefault();
        return !string.IsNullOrEmpty(actionParam.Key) ? actionParam.Value.ToType<string>() : string.Empty;
    }

ToType() is another extension method which internally uses Convert.ChangeType(value, type).

+1  A: 

No, simply because ActionExecutingContext is only valid during OnActionExecuting event (or whatever it's called where it originates from). All you can do is make it look nice by making it an extension method.

public static string GetStateName(this ActionExecutingContext filterContext)
{
    var stateParam = filterContext.ActionParameters.Where(p => p.Key == RouteConst.StateName).FirstOrDefault();
    return !string.IsNullOrEmpty(stateParam.Key) ? stateParam.Value.ToType<string>() : string.Empty;
}

and call it like this

var stateName = filterContext.GetStateName();
Necros