ASP.NET MVC:对操作强制执行 AJAX 请求

发布于 2024-10-02 03:46:32 字数 341 浏览 0 评论 0原文

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

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

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

我设想的是一个 ActionMethodSelectorAttribute ,它可以像 [AcceptVerbs] 属性一样使用。不过,我没有创建此类自定义属性的经验。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

jJeQQOZ5 2024-10-09 03:46:32

创建一个触发 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);           
    }
}

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

然后您可以将其作为 ActionMethods 的属性应用。

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.

夜唯美灬不弃 2024-10-09 03:46:32

就这么简单:

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

我只是忘记了 IsAjaxRequest() 来自哪里,我从我拥有但“丢失”该方法的代码中粘贴。 ;)

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文