Determine if request is PartialView or AJAX reques

2019-06-16 03:26发布

I have to give access rigths to the users of a website. I am doing the filtering here:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
}

The problem is that I cannot distinguish full View request such as 'Index' from PartialViewRequests or AJAX calls requests.

Therefore the page 'Index' has access but the 'PartialViewGridViewForIndex' does not have access.

The property ControllerContext.IsChildAction does not help either.

3条回答
Evening l夕情丶
2楼-- · 2019-06-16 04:02

You can extend HttpRequestExtensions in asp.net Core 2 as below

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;
    }
}

And use it as

 if (!Request.IsAjaxRequest())
 {
    //----
  }
  else
  {
      // -------
  }
查看更多
甜甜的少女心
3楼-- · 2019-06-16 04:02

I would create an Authorization filter by extending the AuthorizeAttribute. I would then put my code in the OnAuthorize override. In the FilterContext object you can look at FilterContext.ActionDescriptor.MethodInfo.ReturnType.Name. For a partial view this will be PartialViewResult.

查看更多
Deceive 欺骗
4楼-- · 2019-06-16 04:24

You could use the IsAjaxRequest extension method to determine if an AJAX request was used to invoke this controller action:

protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
    if (filterContext.HttpContext.Request.IsAjaxRequest())
    {
        // the controller action was invoked with an AJAX request
    }
}
查看更多
登录 后发表回答