Where is Request.IsAjaxRequest() in Asp.Net Core MVC?

前端 未结 4 1351
梦毁少年i
梦毁少年i 2020-11-30 04:10

To learn more about the new exciting Asp.Net-5 framework, I\'m trying to build a web application using the newly released Visual Studio 2015 CTP-6.

Most things looks

4条回答
  •  醉话见心
    2020-11-30 05:07

    I got a little confused, because the title mentioned MVC 5.

    Search for Ajax in the MVC6 github repo doesn't give any relevant results, but you can add the extension yourself. Decompilation from MVC5 project gives pretty straightforward piece of code:

    /// 
    /// Determines whether the specified HTTP request is an AJAX request.
    /// 
    /// 
    /// 
    /// true if the specified HTTP request is an AJAX request; otherwise, false.
    /// 
    /// The HTTP request.The  parameter is null (Nothing in Visual Basic).
    public static bool IsAjaxRequest(this HttpRequestBase request)
    {
      if (request == null)
        throw new ArgumentNullException(nameof(request));
      if (request["X-Requested-With"] == "XMLHttpRequest")
        return true;
      if (request.Headers != null)
        return request.Headers["X-Requested-With"] == "XMLHttpRequest";
      return false;
    }
    

    Since MVC6 Controller seems to be using Microsoft.AspNet.Http.HttpRequest, you'd have to check request.Headers collection for appropriate header by introducing few adjustments to MVC5 version:

    /// 
    /// Determines whether the specified HTTP request is an AJAX request.
    /// 
    /// 
    /// 
    /// true if the specified HTTP request is an AJAX request; otherwise, false.
    /// 
    /// The HTTP request.The  parameter is null (Nothing in Visual Basic).
    public static bool IsAjaxRequest(this HttpRequest request)
    {
      if (request == null)
        throw new ArgumentNullException(nameof(request));
    
      if (request.Headers != null)
        return request.Headers["X-Requested-With"] == "XMLHttpRequest";
      return false;
    }
    

    or directly:

    var isAjax = request.Headers["X-Requested-With"] == "XMLHttpRequest"
    

提交回复
热议问题