ASP.NET MVC ActionFilter - 确定AJAX请求

JP.*_*JP. 17 action-filter asp.net-mvc-3

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

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

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

Ajax请求我不想应用重定向,而是返回错误消息.有没有办法告诉动作过滤器内部,如果这是一个AJAX请求或常规整页(抱歉不确定正确的术语)请求?

提前致谢

J.P

Dar*_*rov 39

您可以使用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");
}
Run Code Online (Sandbox Code Playgroud)