【问题标题】:Cors Error - MVC and Web APICors 错误 - MVC 和 Web API
【发布时间】:2016-01-02 04:09:10
【问题描述】:

我有一个也使用 webapi2 的 MVC 应用程序。 要调用 api 服务,我使用 jquery ajax,如下所示。

$.ajax({
url: GetBaseURL() + '/api/MyController/PutMethod',
type: 'put',
data: dataObject,
contentType: 'application/json',
timeout: AJAX_TIMEOUT,
success: function () {
self.CallOtherFunction();
});

而getbaseURL函数返回content.url("~") 虽然这种方法在某些页面上有效,但它会抛出“跨源请求被阻止:同源策略不允许读取http://api/MyController/PutMethod 的远程资源”错误。

我曾尝试在 cors 上进行谷歌搜索,但无法理解为什么我会遇到此错误,即使我在一个解决方案下同时使用 MVC 和 Webapi,并通过 Visual Studio 运行。

帮助表示赞赏。 谢谢。

【问题讨论】:

  • 您是否已将 API 配置为允许跨域请求? This article 解释了如何设置它。
  • 我不应该对代码进行任何更改,因为该项目已经启动并在生产中运行,没有任何问题。部署应用程序时似乎没有出现 CORS 错误。

标签: asp.net-mvc-4 cors asp.net-web-api2


【解决方案1】:

问题出在您的 WebApi 中。这些项目可能在同一个解决方案中,只有端口可能不同,您会收到 CORS 错误。解决WebApi问题可以看这篇文章:http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

【讨论】:

  • 我已经检查过了,不幸的是 webapi 和网站都配置为使用相同的端口。找不到出路。哎呀!
【解决方案2】:

如果您在 mvc 中调用 api 时遇到此错误,请按照以下步骤操作

第1步:把这个标签放在你的web.config文件中的system.webServer标签下。

 <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*"/>
        <add name="Access-Control-Allow-Headers" value="Content-Type, X-Your-Extra-Header-Key"/>
        <add name="Access-Control-Allow-Methods" value="GET,POST,PUT,DELETE,OPTIONS"/>
        <add name="Access-Control-Allow-Credentials" value="true"/>
      </customHeaders>
    </httpProtocol>
   </system.webServer>

第 2 步 - 将其放入您的 webapi 应用程序的 gloabl.asax.cs 文件中

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

【讨论】:

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