简体   繁体   English

Cors 错误 - MVC 和 Web API

[英]Cors Error - MVC and Web API

I have an MVC application which also uses webapi2.我有一个 MVC 应用程序,它也使用 webapi2。 To call the api services i am using jquery ajax as below.要调用 api 服务,我正在使用 jquery ajax,如下所示。

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

And the function getbaseURL returns content.url("~") While this approach is working out from some pages, it's throwing the "Cross Origin Request Blocked : The same origin policy disallows reading the remote resource at http://api/MyController/PutMethod " error.并且函数 getbaseURL 返回 content.url("~") 虽然这种方法在某些页面上有效,但它会抛出“跨源请求被阻止:相同的源策略不允许读取http://api/MyController/ 上的远程资源PutMethod ”错误。

I have tried googling out on cors but could not understand why I am facing this error, even though I have both MVC and Webapi under one solution, running through visual studio.我曾尝试在 cors 上搜索,但无法理解为什么我会面临此错误,即使我在一个解决方案下同时拥有 MVC 和 Webapi,并通过 Visual Studio 运行。

Help appreciated.帮助表示赞赏。 Thanks.谢谢。

The problem is in your WebApi.问题出在您的 WebApi 中。 The projects could be in the same solution and only the port could be different and you would get the CORS error.项目可以在同一个解决方案中,只有端口可以不同,你会得到 CORS 错误。 To solve the WebApi problem you can read this article: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api要解决 WebApi 问题,您可以阅读这篇文章: http : //www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api

if you facing this error while calling of an api in mvc then you follow the below steps如果您在 mvc 中调用 api 时遇到此错误,请按照以下步骤操作

Step 1 :put this tags in your web.config file in api under the system.webServer tag.第 1 步:将此标签放在 system.webServer 标签下的 api 中的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>

Step 2- put this in gloabl.asax.cs file in your webapi application第 2 步 - 将其放入 webapi 应用程序中的global.asax.cs文件中

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

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

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