【问题标题】:ASP.Net WEB API 2.0 - CORSASP.Net WEB API 2.0 - CORS
【发布时间】:2015-01-06 12:02:05
【问题描述】:

我正在努力解决似乎与 CORS(跨源资源共享)有关的 ASP.Net WEB API 2.0 问题。

在我的 WEB API,services.xyz 站点,我在 System.WebServer 下的 web.config 中进行了以下配置:

  <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://xyz.web" />
    <add name="Access-Control-Allow-Headers" value="Content-Type" />
    <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
  </customHeaders>
</httpProtocol>

在我使用 WEB API 的 ASP.Net 网站 xyz.web 上,我在 WEB API 上调用 GET 方法时没有问题。

$http({ method: 'GET', url: 'http://services.xyz.dk/api/WarningSentences/GetWarningSentencesById?warningSentenceId=' + value })
.success(function (data) {
    deferred.resolve(data);
})

但是当我尝试从 xyz.web 到 services.xyz 的 POST 时,FireFox 告诉我我正在尝试执行不允许的跨源 API 调用。 Chrome 浏览器只是给了我一个 http 状态 405(不允许)。

 $http({
     method: 'POST',
     url: 'http://services.xyz.dk/api/WarningSentences/Update',
     data: value,
     dataType: 'json',
     headers: {"Content-Type": "application/json"}
 })

如果我删除 services.xyz 中的 CORS 配置,一切都会崩溃,这一点很清楚。因此,似乎允许使用 CORS 配置进行 GET API 调用,但不允许使用 POST API 调用...

为什么?

【问题讨论】:

  • HTTP 405 的响应是 Web 服务器告诉客户端该方法(此处为 POST)不能在资源上使用。您是否已将服务器端功能设置为允许 POST 请求?

标签: asp.net asp.net-mvc asp.net-web-api cors


【解决方案1】:

尝试改用“Microsoft.AspNet.WebApi.Cors”库,这是为 Web API 启用 CORS 的更好、更简洁的方法,您无需将标头添加到 web.config 中。

查看this链接了解如何操作的详细信息。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    通过将 Application_BeginRequest 事件添加到 WEB API 网站上的 Global.asax 来解决此问题。

    protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2016-10-07
      • 2015-07-27
      • 2017-12-04
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多