ASP.NET MVC: Enforce AJAX request on an action

可紊 提交于 2019-11-30 02:37:53

问题


I'm looking for a way to enforce a controller's action to be accessed only via an AJAX request.

What is the best way to do this before the action method is called? I want to refactor the following from my action methods:

if(Request.IsAjaxRequest())
    // Do something
else
    // return an error of some sort

What I'm envisioning is an ActionMethodSelectorAttribute that can be used like the [AcceptVerbs] attribute. I have no experience crating such a custom attribute though.


回答1:


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.




回答2:


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. ;)



来源:https://stackoverflow.com/questions/4168341/asp-net-mvc-enforce-ajax-request-on-an-action

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