0
在過去的幾個小時裏,我一直在努力。我所要做的就是像這樣從當前路線中選擇操作參數。這個方法駐留在一個簡單的靜態助手類中。使用助手類訪問ActionExecutingContext
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;
}
但是,我不喜歡在每次必須調用此方法時傳遞上下文的想法。有沒有辦法像HttpContext.Current一樣訪問當前正在執行的上下文?
更新:使用Necros的建議,這是我最終做的。
公共靜態類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()是其內部使用Convert.ChangeType(值,類型)另一種擴展方法。