Determine if request is PartialView or AJAX request in ASP.NET MVC 3

时光毁灭记忆、已成空白 提交于 2019-12-23 07:30:17

问题


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.



来源:https://stackoverflow.com/questions/12892112/determine-if-request-is-partialview-or-ajax-request-in-asp-net-mvc-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!