It is interesting that many ASP.NET developers find this something hard to do, so I write the tips out to reveal that starting from IIS 7 Microsoft makes things so much easier.
Well, I don’t want to duplicate the details as you can easily find it here at Mozilla and probably other places. So simply speaking, such requests are simply HTTP requests with OPTIONS verb.
Unfortunately such preflight requests do not contain user credentials, so IIS automatically responds with 401.2 error page if the ASP.NET content is protected by Windows authentication (and other similar authentication methods) and wants to start a challenge. Note that many browsers such as Firefox won’t respond the challenge, but simply fails the CORS attempts.
Now we know that IIS responds before ASP.NET in most cases, but when fully embracing the integrated pipeline mode we do have a chance to hack.
Remember the fact that ASP.NET HTTP module (derived from
System.Web.IHttpModule) can now be loaded directly by IIS?
That means if we hook to
HttpApplication.BeginRequest event (which triggers before
AuthenticateRequest), we can return whatever response we like.
So to handle the preflight issue, we simply create such a module, and return 200 response at
BeginRequest event with the expected headers (about which headers are expected by the web browsers, please refer to the Mozilla article I linked earlier, as it carefully shows even sample requests/responses).
All module development technical details can be found in the above IIS.net article, so I am not going to provide full source code.
Windows Server 2003/IIS 6 is dying fast, but I believe there are tons of classic mode users. You can still get things done, but in a much more difficult way, as you will have to use C/C++ to write an ISAPI module and perform the logic I described above.
Sounds like finally IIS can support CORS and preflight natively. Check it out.