mvc 只允许ajax访问 HandlerAjaxOnly

有时候我们写一些方法 只想在ajax使用  其他的不想暴露  就可以对方法进行限制

 定义一个类

    [AttributeUsage(AttributeTargets.Method)]
    public class HandlerAjaxOnlyAttribute : ActionMethodSelectorAttribute
    {
        public bool Ignore { get; set; }
        public HandlerAjaxOnlyAttribute(bool ignore = false)
        {
            Ignore = ignore;
        }
        public override bool IsValidForRequest(ControllerContext controllerContext, 
System.Reflection.MethodInfo methodInfo) {
if (Ignore) return true; return controllerContext.RequestContext.HttpContext.Request.IsAjaxRequest(); } }

调用方法 如下

[HandlerAjaxOnly]
public ActionResult yourActionName(string item1, string item2)

{}

posted @ 2016-12-23 10:37  微笑代表淡定.Net  阅读(2332)  评论(0)    收藏  举报