Vijendra Tadavarthy
Vijendra Tadavarthy

Reputation: 41

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.

Upvotes: 3

Views: 2279

Answers (2)

Khushbu Saini
Khushbu Saini

Reputation: 21

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();
            }
        }

Upvotes: 2

dlght
dlght

Reputation: 926

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

Upvotes: 2

Related Questions