ASP.NET MVC: Enforce AJAX request on an action

跟風遠走 提交于 2019-11-30 18:18:40
bmancini

Create an ActionFilter that fires OnActionExecuting

public class AjaxActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
            filterContext.Result = new RedirectResult(//path to error message);           
    }
}

Setting the filter's Result property will prevent execution of the ActionMethod.

You can then apply it as an attribute to your ActionMethods.

Its as simple as this:

public class AjaxOnly : ActionMethodSelectorAttribute
{
    public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
    {
        return controllerContext.HttpContext.IsAjaxRequest();
    }
}

I just forget where IsAjaxRequest() comes from, I'm pasting from code I have but "lost" that method. ;)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!