ASP.NET MVC:对操作强制执行A​​JAX请求

Rem*_*mus 11 ajax asp.net-mvc actionmethod controller-action

我正在寻找一种方法来强制执行控制器的操作只能通过AJAX请求访问.

在调用action方法之前执行此操作的最佳方法是什么?我想从我的动作方法重构以下内容:

if(Request.IsAjaxRequest())
    // Do something
else
    // return an error of some sort
Run Code Online (Sandbox Code Playgroud)

我想象的是ActionMethodSelectorAttribute可以像[AcceptVerbs]属性一样使用.我没有经验包装这样的自定义属性.

bma*_*ini 17

创建一个触发OnActionExecuting的ActionFilter

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

设置过滤器的Result属性将阻止执行ActionMethod.

然后,您可以将其作为属性应用于ActionMethods.