简体   繁体   English

Web API 2 - CORS仅适用于HTTPS(不是HTTP)

[英]Web API 2 - CORS only works over HTTPS (not HTTP)

All, 所有,

I have a really simple Web API 2 project that I'm working on. 我有一个非常简单的Web API 2项目,我正在努力。 For some reason I cannot get CORS to work properly unless I put it in the web.config file. 出于某种原因,我不能让CORS正常工作,除非我把它放在web.config文件中。 I followed the instructions on the MSDN article and this ASP.NET article , but I must be missing something. 我按照MSDN文章和这篇ASP.NET文章中的说明进行操作,但我必须遗漏一些东西。

Global.asax.cs 的Global.asax.cs

protected void Application_Start()
{
    WebApiConfig.Register(GlobalConfiguration.Configuration);
}

WebApiConfig.cs WebApiConfig.cs

public static void Register(HttpConfiguration config)
{
    config.EnableCors(new EnableCorsAttribute("*","*","*"));

    config.MapHttpAttributeRoutes();
}

JavaScript JavaScript的

    $.ajax({
        url: '//myapidomain.com/buildings'
    }).done(function (data) {
        var theList     = $('.buildings'),
            theListHTML = "",
            response    = JSON.parse(data);

        $.each(response.Buildings.Data, function () {
            theListHTML += '<li>' + this.Description + '</li>';
        });
        theList.html(theListHTML);
    });

I've looked at just about every single Stack Overflow (such as this one ) and MSDN forum post (like this one ), and from what I can tell, this should be working. 我已经看过几乎每一个Stack Overflow(比如这个 )和MSDN论坛帖子(就像这一个 ),从我所知道的,这应该是有效的。 The app is hosted on an IIS 8 server running 4.0. 该应用程序托管在运行4.0的IIS 8服务器上。

Update 更新

It appears to be something with the request itself (or rather IIS configuration). 它似乎与请求本身(或更确切地说是IIS配置)有关。 If I send the request over HTTP, then it fails (no access-control headers get sent back). 如果我通过HTTP发送请求,则它会失败(没有发回访问控制头)。 However, if I request it over HTTPS, everything works fine. 但是,如果我通过HTTPS请求它,一切正常。

Solution

Our hosting environment was intercepting the non-HTTPS requests and forcing them to HTTPS. 我们的托管环境拦截了非HTTPS请求并强制它们使用HTTPS。 When it does this it returns a 304 which jQuery's method doesn't know how to handle. 当它执行此操作时,它返回304,jQuery的方法不知道如何处理。 The solution is either to just always make the request over HTTPS (preferred) OR to handle this situation yourself/find an alternative library/plugin that handles this scenario. 解决方案要么总是通过HTTPS(首选)发出请求,要么自己处理这种情况/找到处理这种情况的替代库/插件。

Solution

Our hosting environment was intercepting the non-HTTPS requests and forcing them to HTTPS. 我们的托管环境拦截了非HTTPS请求并强制它们使用HTTPS。 When it does this it returns a 304 which jQuery's method doesn't know how to handle. 当它执行此操作时,它返回304,jQuery的方法不知道如何处理。 The solution is either to just always make the request over HTTPS (preferred) OR to handle this situation yourself/find an alternative library/plugin that handles this scenario. 解决方案要么总是通过HTTPS(首选)发出请求,要么自己处理这种情况/找到处理这种情况的替代库/插件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM