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

时间:2021-08-18 00:48:38

大多数事情看起来真的很有希望,但我似乎找不到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>The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref/> 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>The HTTP request.</param><exception cref="T:System.ArgumentNullException">The <paramref/> 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"