我最終選擇的路線是反射和包含存儲在Application []中的相關控制器中所有有效操作的字典。通過檢查方法的ReturnType並驗證它是(或派生自)ActionResult並且它不是Private來確定有效的Action。我可以做更多的檢查,但現在已經足夠了。
public static bool MethodIsAction(MethodInfo method)
{
if (method == null)
throw new ArgumentNullException("Invalid Parameter: method cannot be null.");
if (method.ReturnType != typeof(ActionResult) && method.ReturnType.BaseType != typeof(ActionResult))
return false;
if (method.IsPrivate)
return false;
return true;
}
行動的字典是建立與內部的Application_Start下面的方法:
public static Dictionary<string, MethodInfo> GetActionDictionary(Type controller)
{
Dictionary<string, MethodInfo> dict = null;
var methods = controller.GetMethods().Where(MethodIsAction);
if (methods.Any())
{
dict = new Dictionary<string, MethodInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var action in methods)
dict.Add(action.Name, action);
}
return dict;
}
當用戶請求一個合格的動作,我只是在字典點動作的名稱,如果一個MethodInfo的存在對於行動名稱我調用它。雖然它仍然需要反思,但至少應該進行優化,以便在應用程序運行時只發生一次。
不幸的是,這個選項對於我的場景來說並不是真的可行,因爲路由決策是如何實現的。儘管如此,這確實給了我一個處理潛在問題的另一種方法。如果我預先防止了路由錯誤的可能性,那麼我至少可以部分控制手頭的問題。 – 2009-10-25 17:50:38