C#MVC检测XMLHttpRequest

问题描述 投票:1回答:3

我在C#Controller中尝试了以下内容

使用以下命名空间

 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();
    }

它们都不适合我。我可以调试请求,但我找不到任何告诉我这是一个xhrXMLHttpRequest

我正在调用控制器动作:

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类型请求:enter image description here

如何在C#Controller或XHR文件中检测.cshtml请求?

c#
3个回答
2
投票

您可以执行以下操作:

    // 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请求与任何其他类型的请求。


0
投票

您没有导入扩展AjaxRequestExtensions。这就是你在第一行遇到错误的原因

Request.IsAjaxRequest(); //这一行告诉我“HttpRequest不包含IsAjaxRequest的定义..(你错过了一个using指令吗?)”


0
投票

正如拜伦琼斯在answer指出的那样,我需要将MLHttpRequest.setRequestHeader()设置为我自己,如果你按照链接进行操作,你会发现它就像添加一样简单

oReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

所以从这样的问题更新了我的代码:

// C# needs the line:
public IActionResult Create()
    {
        ViewData["xmlHttpRequest"] = false;
        if (HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
            ViewData["xmlHttpRequest"] = true;
        }

        return View();
    }


// and javascript like so:
function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "https://localhost:5001/Movies/Create");
oReq.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); // this is the only new line
oReq.send();

From the documentation说明了

XMLHttpRequest方法setRequestHeader()设置HTTP请求标头的值。使用setRequestHeader()时,必须在调用open()之后调用它,但在调用send()之前。如果使用相同的标头多次调用此方法,则会将值合并到一个请求标头中。

请点击链接获取更多信息。

© www.soinside.com 2019 - 2024. All rights reserved.