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