为什么我的 ASP.NET MVC 站点中的这个 AJAX 请求会触发预检?

Why is this AJAX request in my ASP.NET MVC site triggering a preflight check?

我有一个 ASP.NET MVC 5 项目,其中一个页面有一些 JavaScript 在服务器上调用 API 运行 宁 ASP.NET WebApi 项目。这两个项目通常 运行 在不同的域上,但在本地它们只是在 localhost 上的不同端口上。此 JavaScript 正在发出 GET 请求,但是当我查看网络日志时,正在发出 OPTIONS 请求,而 WebApi returns 405 Method Not Authorized.

根据我的研究,我知道 this is a "preflight" check that is sometimes triggered for AJAX calls, and I know that ASP.NET WebApi doesn't support OPTIONS by default, so that's why I'm getting the 405. However, the preflight check is supposed to be skipped when certain conditions are met,并且这里已经满足了这些条件。你自己看;以下是 AJAX 请求的(匿名)完整 JS 代码:

var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:12345/api/SomeAction?someArg=" + someArg;

xmlhttp.onreadystatechange = function () {
  if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
    // [snip], process the result here
  }
};

xmlhttp.open("GET", url, true);
xmlhttp.send();

为什么这个简单的请求会触发预检?

问题是由于 Application Insights 在 MVC 项目中加载了一些额外的 JavaScript。

我通过使用调试器进入 xmlhttp.send() 调用发现了这一点,我最终注意到我在 ai.0.js 中。 AppInsights 中的该文件覆盖了 XMLHttpRequestadds a couple custom headers to the request 的定义,这导致需要进行预检。

因此有两种可能的解决方案:

  1. 禁用 Application Insights 并删除其自定义 JavaScript。
  2. 在 API 项目中实施 OPTIONS 处理。

Supporting OPTIONS is likely the better solution,所以我最终可能会这样做,但删除 AppInsights 更快,所以我现在就这样做。我在 _Layout.cshtml 视图中删除了以 var appInsights = window.appInsights... 开头的 <script> 标签,并解决了这个问题。