2011-12-03 32 views

回答

-1

那麼,HttpPostAttribute是密封的。但你可以窺探它(ILSpy是你的朋友)的靈感:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] 
public sealed class HttpPostAttribute : ActionMethodSelectorAttribute 
{ 
    private static readonly AcceptVerbsAttribute _innerAttribute = new AcceptVerbsAttribute(HttpVerbs.Post); 
    public override bool IsValidForRequest(ControllerContext controllerContext, MethodInfo methodInfo) 
    { 
     return HttpPostAttribute._innerAttribute.IsValidForRequest(controllerContext, methodInfo); 
    } 
} 

很簡單吧?你只需要創建完全相同的邏輯,作爲回報,把

return (yourCustomCondition) && HttpPostAttribute._innerAttribute.IsValidForRequest(controllerContext, methodInfo); 
+1

這個答案是不是真的,因爲的內部邏輯的通用解決方案HttpPost屬性可能會在更高版本的MVC中更改,然後此解決方案將停止工作。在這種情況下,@gdoron提供的答案要好得多。 – Anton

3

我認爲這是你在找什麼:

public class PostActiongFilter : ActionFilterAttribute 
{ 
    public virtual void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
     var actionName = filterContext.ActionDescriptor.ActionName; 
     var actionParams = filterContext.ActionDescriptor.GetParameters 
     var actionParamsTypes = actionParams.Cast<ParameterDescriptor>() 
             .Select(x => x.ParameterType).ToArray(); 
     var controllerType = filterContext.Controller.GetType();    
     var actionMethodInfo = controllerType.GetMethod(actionName, 
                 actionParamsTypes, null);    
     var isMethodPost = actionMethodInfo.IsDefiend(typeof(HttpPostAttribute), 
                 false); 

     if (!isMethodPost) 
      return; 

     // Do what you want for post here...       
    } 
} 
+0

更正在您的最後一行:var isMethodPost = actionMethodInfo.IsDefined(typeof(HttpPostAttribute),false); – Ryk

+1

@瑞克,謝謝。順便說一句,這個網站允許你編輯\建議你想要編輯。無論如何,謝謝你的發現。 – gdoron

相關問題