确定ASP.NET MVC 3中的请求是否为PartialView或AJAX请求

我必须为网站用户提供访问权限。 我在这里做过滤:

protected override void OnActionExecuting(ActionExecutingContext filterContext) { } 

问题是我无法区分完整的View请求,例如’Index’与PartialViewRequests或AJAX调用请求。

因此页面'Index'具有访问权限,但'PartialViewGridViewForIndex'没有访问权限。

属性ControllerContext.IsChildAction也没有帮助。

您可以使用IsAjaxRequest扩展方法来确定是否使用AJAX请求来调用此控制器操作:

 protected override void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.HttpContext.Request.IsAjaxRequest()) { // the controller action was invoked with an AJAX request } } 

您可以在asp.net Core 2中扩展HttpRequestExtensions,如下所示

 public static class HttpRequestExtensions { private const string RequestedWithHeader = "X-Requested-With"; private const string XmlHttpRequest = "XMLHttpRequest"; public static bool IsAjaxRequest(this HttpRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.Headers != null) { return request.Headers[RequestedWithHeader] == XmlHttpRequest; } return false; } } 

并用它作为

  if (!Request.IsAjaxRequest()) { //---- } else { // ------- } 

我将通过扩展AuthorizeAttribute来创建一个Authorizationfilter。 然后我会将我的代码放在OnAuthorize覆盖中。 在FilterContext对象中,您可以查看FilterContext.ActionDescriptor.MethodInfo.ReturnType.Name 。 对于局部视图,这将是PartialViewResult