0

I have an ASP.NET MVC 5 project, and one of the pages has some JavaScript that calls an API on a server that is running an ASP.NET WebApi project. The two projects normally run on different domains, but locally they are just on different ports on localhost. This JavaScript is making a GET request, but when I watch the network log an OPTIONS request is being made instead, and the WebApi returns 405 Method Not Authorized.

From my research, I know that 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, and those conditions have been met here. See for yourself; the following is the (anonymized) entirety of the JS code for the AJAX request:

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

Why is this simple request triggering a preflight check?

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67

1 Answers1

0

The issue was due to some additional JavaScript loaded by Application Insights in the MVC project.

I discovered this by stepping into the xmlhttp.send() call with the debugger, where I eventually noticed I was in ai.0.js. That file from AppInsights overrides the definition of XMLHttpRequest, and adds a couple custom headers to the request, which causes the preflight check to be required.

Thus there are two possible solutions:

  1. Disable Application Insights and remove its custom JavaScript.
  2. Implement OPTIONS handling in the API project.

Supporting OPTIONS is likely the better solution, so I will likely do that eventually, but removing AppInsights is faster, so I'm doing that for now. I removed the <script> tag that started with var appInsights = window.appInsights... in my _Layout.cshtml view, and that fixed the issue.

Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
  • you should also post this as an issue on the AI javascript sdk https://github.com/Microsoft/ApplicationInsights-JS/issues . I don't know why the presence of AI would be forcing a CORS check by the browser. – John Gardner May 10 '17 at 23:57
  • @JohnGardner: I hadn't posted an issue there because I didn't think it was necessarily a bug, just an unfortunate side-effect. I believe it is the custom headers that AI adds that forces the preflight check (see the file on GitHub I linked to in my answer). Let me know if you think it actually is a bug, and I can open up an issue. – Scott Weldon May 15 '17 at 20:05