Asp.net mvc 4 Cors错误-MVC和Web API

Asp.net mvc 4 Cors错误-MVC和Web API,asp.net-mvc-4,cors,asp.net-web-api2,Asp.net Mvc 4,Cors,Asp.net Web Api2,我有一个MVC应用程序,它也使用webapi2。 为了调用api服务,我使用jQueryAjax,如下所示 $.ajax({ url: GetBaseURL() + '/api/MyController/PutMethod', type: 'put', data: dataObject, contentType: 'application/json', timeout: AJAX_TIMEOUT, success: function () { self.CallOtherFunction();

我有一个MVC应用程序,它也使用webapi2。 为了调用api服务,我使用jQueryAjax,如下所示

$.ajax({
url: GetBaseURL() + '/api/MyController/PutMethod',
type: 'put',
data: dataObject,
contentType: 'application/json',
timeout: AJAX_TIMEOUT,
success: function () {
self.CallOtherFunction();
});
函数getbaseURL返回content.url(“~”) 当这种方法在某些页面上运行时,它抛出了“跨源请求被阻止:同源策略不允许读取远程资源”错误

我曾在cors上尝试过谷歌搜索,但无法理解为什么我会面临这个错误,尽管我在一个解决方案中使用了MVC和Webapi,通过VisualStudio运行

谢谢你的帮助。
谢谢。

问题出在您的WebApi中。项目可以在同一个解决方案中,只有端口可以不同,您将得到CORS错误。要解决WebApi问题,您可以阅读本文:

如果在mvc中调用api时遇到此错误,请执行以下步骤

步骤1:将此标记放在api中system.webServer标记下的web.config文件中

 <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>

您是否已将API配置为允许跨源请求?解释如何设置它。我不应该在代码中做任何更改,因为项目已经在生产中启动并运行,没有任何问题。部署应用程序时,CORS错误似乎没有出现。我已经检查了这一点,不幸的是,webapi和Web都配置为使用同一端口。找不到出路。哎呀!
protected void Application_BeginRequest()
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.End();
                Response.Flush();
            }
        }