Determine if request is PartialView or AJAX reques

2019-06-16 04:15发布

问题:

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.

回答1:

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


回答2:

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:

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.