2012-10-15 158 views
9

我必须为网站的用户提供访问权限。 我在这里做过滤:确定请求是ASP.NET MVC中的PartialView还是AJAX请求3

protected override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
} 

的问题是,我无法分辨完整View要求如PartialViewRequests“索引”或AJAX调用请求。

因此,页面'Index'有权访问,但'PartialViewGridViewForIndex'无权访问。

财产ControllerContext.IsChildAction也没有帮助。

回答

31

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

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

谢谢!我正在测试它,看它是否有效。我会回来的反馈。 –

+0

我已经测试过它,它工作。不过,我不禁要问自己,局部视图渲染是否由AJAX请求完成。你有什么想法吗? –

+0

“IsAjaxRequest”告诉你当前请求是否是AJAX请求。 –

0

我会通过延长AuthorizeAttribute创建授权过滤器。然后我会把我的代码放在OnAuthorize重写中。在FilterContext对象中,您可以查看FilterContext.ActionDescriptor.MethodInfo.ReturnType.Name。对于局部视图,这将是PartialViewResult

0

您可以在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 
    { 
     // ------- 
    }