Tuesday, April 11, 2017

Advanced configuration and implementation in enabling Cross-Origin Requests in ASP.NET Web API 2

After we deploy the Web Api or WCF to cloud or in the public network. It means that we already expose the data to any one who know the url of the Web Api or WCF.

I will skip the introduction to setting up the Cross-Origin Requests in ASP.NET Web API 2 here.

For more information about the CORS for Web Api. you can visit MSDN link

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


i will only focus on the a little bit advance topic on CORS implementation, since i had spend
extend period of time to complete the implementation.


1. control the CORS with custom setting in web.config file.

the configuration setting will allow us to add more domains without any code change and depolyment, we only need system admin to add more domain in the name attribute that separate by
comma.

<configSections>
    <section name="CORSSettings" type="MyApp.CORSSettings, MyApp" />
  </configSections>


 <CORSSettings>
    <CorsSupport>
      <Domain Name="http://firstdomain,http://seconddomain,http://thirddomain" AllowMethods="*" AllowHeaders="*" AllowCredentials="true">
      </Domain>
    </CorsSupport>
  </CORSSettings>


2. Server Side Implementation  

 In the WebApiConfig class

added the following code to enable the CORS globally

var cORSSettings = ConfigurationManager.GetSection("CORSSettings") as CORSSettings;
            if (cORSSettings == null)
                throw new InvalidOperationException("Missing CORS configuration");
            var domains = cORSSettings.CorsSupport.OfType<CorsDomain>();
            foreach (var domain in domains)
            {
                var cors = new EnableCorsAttribute(domain.Name, domain.AllowHeaders, domain.AllowMethods);
                cors.SupportsCredentials = true;
                config.EnableCors(cors);
            }

please ensure the CORS object with property SupportsCredentials to be True, if your web api is configured with windows authentication and disable anonymous access. otherwise you will always receive XMLHttpRequest Network Error




3. Client Side Implementation

Even though you have enable the cors with SupportCredentials, you still will encouter the PreFlight request OPTIONS Error like
  "Origin http://YourDomain is not allowed by Access-Control-Allow-Origin"

when you use .ajax the jquery wrappper to execute the client call

$.ajax({
    type: 'get',
    url: 'http://www.example.com/api/test',
    xhrFields: {
        withCredentials: true
    }

actually we should use this XMLHttpRequest directly to call the web api to solve the preFlight request OPTIONS Error


                    var xmlHttpRequest = new XMLHttpRequest();
                    xmlHttpRequest.open('GET', sWCFUrl, true);
                    xmlHttpRequest.withCredentials = true;
                    xmlHttpRequest.onreadystatechange = processData;
                    xmlHttpRequest.send();
     

 I hope this post can help solve the headache on CORS implementation especiallly with windows authentication eanble and anonymous access diable.







No comments:

Post a Comment