1

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?

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't that allow any origin to connect? Sorry I am new to this :)
Also by using [EnableCors(origins: "http://mywebsite.com", headers: "*", methods: "*")] I think I've already configured the server to allow my site to access it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.