开发者

ASP.NET MVC: Enforce AJAX request on an action

开发者 https://www.devze.com 2023-01-25 01:17 出处:网络
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

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 开发者_如何学Pythonan 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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消