我必须为网站用户提供访问权限。我在这里进行过滤:
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
问题是我无法区分完整的视图请求,例如"索引"与部分视图请求或 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
}
}
您可以在 Core 2 中扩展 HttpRequestExtensions,如下所示 asp.net
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
来创建授权过滤器。 然后,我将我的代码放在OnAuthorize
覆盖中。 在FilterContext
对象中,您可以查看FilterContext.ActionDescriptor.MethodInfo.ReturnType.Name
。 对于部分视图,这将PartialViewResult
。