WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c# – Asp.Net Core MVC中Request.IsAjaxRequest()在哪里?

Posted on 2019-09-21 16:21  WebEnh  阅读(1523)  评论(0编辑  收藏  举报
要了解有关新的令人兴奋的Asp.Net-5框架的更多信息,我正在使用最新发布的Visual Studio 2015 CTP-6来构建一个Web应用程序。

 

大多数事情看起来真的很有希望,但我似乎找不到Request.IsAjaxRequest() – 一个在旧的MVC项目中经常使用的功能。

有没有更好的方法来做到这一点 – 这使得他们删除这种方法 – 或者是“隐藏”在别的地方?

感谢任何建议,在哪里找到它或做什么改为!

 
我有点困惑,因为标题提到了MVC 5。

 

搜索Ajax in the MVC6 github repo doesn’t give any relevant results,但您可以自己添加扩展。从MVC5项目中进行的解压缩代码很简单:

 

/// <summary>
/// Determines whether the specified HTTP request is an AJAX request.
/// </summary>
/// 
/// <returns>
/// true if the specified HTTP request is an AJAX request; otherwise, false.
/// </returns>
/// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
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;
}

由于MVC6 Controller似乎使用Microsoft.AspNet.Http.HttpRequest,您必须通过对MVC5版本引入少量调整来检查request.Headers collection是否适合标题:

 

/// <summary>
/// Determines whether the specified HTTP request is an AJAX request.
/// </summary>
/// 
/// <returns>
/// true if the specified HTTP request is an AJAX request; otherwise, false.
/// </returns>
/// <param name="request">The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref name="request"/> parameter is null (Nothing in Visual Basic).</exception>
public static bool IsAjaxRequest(this HttpRequest request)
{
  if (request == null)
    throw new ArgumentNullException("request");

  if (request.Headers != null)
    return request.Headers["X-Requested-With"] == "XMLHttpRequest";
  return false;
}

或直接:

 

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