简体   繁体   中英

Cors Error - MVC and Web API

I have an MVC application which also uses webapi2. To call the api services i am using jquery ajax as below.

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

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.

Help appreciated. Thanks.

The problem is in your WebApi. The projects could be in the same solution and only the port could be different and you would get the CORS error. 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

if you facing this error while calling of an api in mvc then you follow the below steps

Step 1 :put this tags in your web.config file in api under the system.webServer tag.

 <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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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