jquery - Ajax POST 请求时出现 .Net MVC API Access-Control-Allow-Origin 错误

标签 jquery ajax asp.net-mvc api

我在 VS2013 中有一个 .Net 解决方案,在不同的端口上有多个项目。我在其中两个项目之间来回发送数据,主要是 localhost:4348 上的 API 项目和 localhost:33630 上的前端项目。

我正在使用 jQuery 对 API 进行 ajax 调用,并通过 POST 请求发送数据,POST 请求的示例:

$.ajax({
    type: "POST",
    url: 'http://localhost:4348/api/Viewer/GetSearchResult',
    data: searchObject,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (responseData, textStatus, jqXHR) {
        console.log(responseData);
    },
    error: function (responseData, textStatus, errorThrown) {
        console.log("Text status:", textStatus);
    }
});

searchObject 结构如下,其中的项目在 ajax 调用之前的某个时刻被填充:

searchObject.generalSearchList = [];
searchObject.indexesSearchList = [];
searchObject.searchType = '';
searchObject.language = '';
searchObject.id = '';
searchObject.selector = '';

API 项目不允许我将以下设置添加到 Web.config 文件:

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*" />
  </customHeaders>
</httpProtocol>

这样做会在我尝试调用的任何 API 上引发此错误:

XMLHttpRequest cannot load http://localhost:4348/api/Viewer/GetTrees?Lang=en-US. The 'Access-Control-Allow-Origin' header contains multiple values 'http://localhost:33630, *', but only one is allowed. Origin 'http://localhost:33630' is therefore not allowed access.

因此,如果没有设置该选项,当我尝试使用 POST 方法调用 API 时,会收到以下错误:

XMLHttpRequest cannot load http://localhost:4348/api/Viewer/GetSearchResult. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:33630' is therefore not allowed access. The response had HTTP status code 500.

contentType 设置为 application/json; charset=utf-8 触发 OPTIONS 类型的预检请求。 沿着 Visual Studio 的思路,它在 GET 请求上添加对源 http://localhost:33630 的权限,但不在 OPTIONS 上添加权限> 请求。而且我无法覆盖 Web.config 文件中提到的权限。

在此处发布之前,我已经做了很多研究并测试了许多场景,包括添加

<add name="Access-Control-Allow-Methods" value="*" />
<add name="Access-Control-Allow-Headers" value="*" />

到 API 项目中的 web.config 文件。

不用说,我非常想了解错误的原因并解决它,因为我已经被这个问题困扰了大约一周。在 Chrome 和 Firefox 上进行了测试。

最佳答案

您也可以在 WebApiConfig.cs 中启用 CORS。

  1. 安装 nuget Microsoft.AspNet.WebApi.Cors
  2. 在 WebApiConfig.cs 中启用 cors

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            var cors = new EnableCorsAttribute("*", "*", "*");
            config.EnableCors(cors);
            // Other config lines
        }
    }
    

这将全局启用 CORS,您可以使用 来装饰您的 api Controller 甚至单个 api 方法

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class TestController : ApiController
{
    // Controller methods not shown...
}

针对特定 Controller 或方法。 您可以阅读有关在 WebAPI 项目中启用 CORS 的更多信息: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

关于jquery - Ajax POST 请求时出现 .Net MVC API Access-Control-Allow-Origin 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32307586/

相关文章:

jQuery - 正则表达式问题 - 获取 3 '/'(斜杠)之间的 href 地址

javascript - 计算 <li> 内 <div> 元素的数量

C#以更少的内存消耗从服务器下载大文件

javascript - jQuery 中文本框值中的数字不可更改

javascript - 带有 jQ​​uery 插件的 jQuery 对象文字或模块模式

javascript - AngularJS:全局访问服务?

javascript - AJAX 联系表单在 Wordpress 中不起作用

javascript - 在 codeIgniter 中使用单个表进行动态下拉

asp.net-mvc - 部署的 ASP.NET MVC 4 项目无法运行

C# Web 应用程序 -> 代理所有请求 -> 从另一个 Web 应用程序返回内容(反向代理)