我已经在我的C#控制器中尝试了以下操作
使用了以下命名空间
using System;
using System.Web;
using System.Web.Mvc;
以及IActionResult Create()
方法中的以下“内容”
// GET: Movies/Create
public IActionResult Create()
{
Request.IsAjaxRequest(); // this line tells me "HttpRequest does not contain a defintion for IsAjaxRequest .. (are you missing a using directive?)"
string method = HttpContext.Request.Method;
string requestedWith = HttpContext.Request.Headers["X-Requested-With"];
HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest";
new HttpRequestWrapper(System.Web.HttpContext.Current.Request).IsAjaxRequest()
return View();
}
他们都不适合我。我可以调试请求,但是我找不到任何东西来告诉我这是一个xhr
或XMLHttpRequest
。
我像这样调用控制器操作:
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://localhost:5001/Movies/Create");
oReq.send();
浏览器开发工具告诉我这是一个XHR类型请求:
如何在C#控制器或.cshtml
文件中检测XHR
请求?
发布于 2019-03-05 07:32:36
您可以执行以下操作:
// GET: Movies/Create
public IActionResult Create()
{
string requestedWith = HttpContext.Current.Request.Headers["X-Requested-With"];
if(requestedWith == "XMLHttpRequest")
{
// Do whatever you want when an AJAX request comes in here....
}
return View();
}
请注意,在现实中,没有万无一失的方法来检测AJAX请求-- X-Requested-With
头可以由开发人员或客户端库(如jQuery )随意发送。所以不能保证这个头会被发送,当然,除非你是使用这个服务的唯一客户端代码的开发者。对于服务器而言,AJAX请求与任何其他类型的请求没有什么区别。
https://stackoverflow.com/questions/54991671
复制相似问题