【问题标题】:ASP.NET MVC ActionFilter - Determine if AJAX RequestASP.NET MVC ActionFilter - 确定是否有 AJAX 请求
【发布时间】:2011-12-07 20:37:28
【问题描述】:

我正在使用 ActionFilter 来确定用户在执行操作之前是否有权访问特定资源,例如 Account 对象(a la Rhino Security)。这是一个全局过滤器,如果授权值失败,它会重定向到错误页面

我正在使用以下代码,它适用于整页请求:

filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
filterContext.Result = new RedirectResult("~/Error/AuthorizationError");

Ajax 请求我不想应用重定向,而是返回错误消息。有没有办法在操作过滤器内部判断这是 AJAX 请求还是常规整页请求(抱歉,不确定术语是否正确)?

提前致谢

日本

【问题讨论】:

    标签: asp.net-mvc-3 action-filter


    【解决方案1】:

    您可以使用IsAjaxRequest 扩展方法:

    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
        // it was an AJAX request
        ...
    }
    else
    {
        // it was a standard request
        filterContext.Controller.TempData["ErrorMessage"] = string.Format("You are not authorized to perform operation: {0}", operation);
        filterContext.Result = new RedirectResult("~/Error/AuthorizationError");
    }
    

    【讨论】:

    • 这看起来正是我们想要做的。但是......由于某种原因,当它是一个 AJAX 请求时,条件 filterContext.HttpContext.Request.IsAjaxRequest() 不会恢复为真。另外...您如何将用户从 ajax 请求重定向到新页面?
    • @bubbleking 我希望我能给你一个好的答案。我什至不记得我们正在尝试使用哪个页面。对不起:(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多