Jay
Jay

Reputation: 5074

ASP.NET Web Forms: No 'Access-Control-Allow-Origin' header is present on the requested resource

I know that similar questions have been asked but I tried almost all of them and none of them worked.

I need to simply allow a separate website (mywebsite.com) to access the Web API Methods of another web service (myserver.com) (coded on ASP.NET Web API and Hosted on azure)

Server code:

public class MyController : ApiController
{
     [EnableCors(origins: "http://mywebsite.com", headers: "*", methods: "*")]
     [Route("api/sendrequest")]
     [HttpPost]
     public IHttpActionResult SendRequest()
     {
          string response = "You made it to the server!";

          return Ok(new { response });
     }
}

Client side Ajax request:

function send_data() {

    var values = "Hello from Client";

    $.ajax({
        url: "https://myserver.com/api/mycontroller/sendrequest",
        type: "POST",
        data: values,
        success: function (response) {
            alert(response);
            console.log(response);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus, errorThrown);
            alert("error");
        }

    });
}

Even though I've allowed this specific website to communicate with the server, it still returns me this error in the console:

XMLHttpRequest cannot load https://myserver.com/api/mycontroller/sendrequest.

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.com' is therefore not allowed access. The response had HTTP status code 500.

What am I doing wrong here? Should I include any additional details in the request header?

Upvotes: 1

Views: 4103

Answers (1)

Kahbazi
Kahbazi

Reputation: 14995

You need to config your web.config !

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
  <system.webServer>
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET,POST,OPTIONS" />
        <add name="Access-Control-Allow-Headers" value="Content-Type, soapaction" />
      </customHeaders>
    </httpProtocol>
  </system.webServer>
</configuration>

Upvotes: 2

Related Questions