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


要了解有关新的令人兴奋的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"
 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM