← back to the blog


Browser cross domain example - asp.net

Posted in ASP.NET by dake

Simple example of how to achieve cross domain access at asp.net, following example is the simple and lazy way which just make it working by modify web.config.

let's assume you have following  two site, client-site.com is trying to access server-site.com's ajax api, /api/getMyData

  • client-site.com
  • server-site.com
    • contains /api/getMyData

So, what's you have to do at server-site.com site is following, you're let your server to return Access-Control-Allow-Origin header to the http response. 


 <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="http://client-site.com"/>
      </customHeaders>
    </httpProtocol>
  </system.webServer>

client-site.com site you can just call as following, assume your api is server-site.com/api/getMyData


<script> 
$.ajax({ url: "http://server-site.com/api/getMyData" }).then(function () {
            console.info("done with call server-site.com's api");
        });
</script>

for more detail information about how to enable cross for specific http method, specific site, or other usefull library. I'll add reference at here or code example.

 

Enabling Cross-Origin Requests in ASP.NET Web API 2