ASP.NET MVC:实施一项行动AJAX请求 [英] ASP.NET MVC: Enforce AJAX request on an action

查看:252
本文介绍了ASP.NET MVC:实施一项行动AJAX请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方式来执行控制器的动作只能通过AJAX请求进行访问。

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

什么我构想是 ActionMethodSelectorAttribute ,可以像的[AcceptVerbs] 属性一起使用。我没有经验,虽然装箱这样的自定义属性。

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.

推荐答案

创建一个触发OnActionExecuting的ActionFilter

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

设置过滤器的结果属性将美元ActionMethod的对$ pvent执行。

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

您就可以申请它作为你的ActionMethods的属性。

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

这篇关于ASP.NET MVC:实施一项行动AJAX请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆