WebEnh

.net7 mvc jquery bootstrap json 学习中 第一次学PHP,正在研究中。自学进行时... ... 我的博客 https://enhweb.github.io/ 不错的皮肤:darkgreentrip,iMetro_HD
随笔 - 1079, 文章 - 1, 评论 - 75, 阅读 - 174万
  首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

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

Posted on   WebEnh  阅读(1559)  评论(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"
 
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示

喜欢请打赏

扫描二维码打赏

了解更多