Don of the Day

Don of the Day


Adventures in software development with Xamarin and the Web

Software developer, building things with code in sunny Scottsdale, AZ.

Share


Twitter


ServiceStack and CORS

Don FitzsimmonsDon Fitzsimmons

If you’ve ever tried to make cross-domain calls with a web browser, you have probably run into the infamous cross domain access error that prevents one domain from making ajax calls to another. In my case, I’m using ServiceStack as my Web API and I have an ASP.Net MVC client application that makes some POST and GET calls via jQuery.

If you have control over your server, it’s likely that you can implement CORS which will allow you to modify the Access-Control-Allow-Origin HTTP header, making your browser happy and your ajax calls work across domains. ServiceStack inlcudes a CORS plugin, which can be enabled globally or even per-service. But, I found that it just wouldn’t work for me. I’m not sure why, but nothing I tried worked.

CORS in ServiceStack (in the host configure section)

Plugins.Add(new CorsFeature()); CorsFeature(allowedOrigins:"*", allowedMethods:"GET, POST, PUT, DELETE, OPTIONS", allowedHeaders:"Content-Type", allowCredentials:false);

I later found out that IIS has support for CORS (I believe IIS 7 and above). Once I added my CORS headers to my web.config, I was almost good to go.

CORS in IIS Web.Config

The next problem was that, when using CORS, your client might need to make a pre-flight OPTIONS request to check if it’s allowed to access the cross-domain resource, but my service didn’t allow the OPTIONS verb. I read up on Stack Overflow that you can enable a global filter for requests that make an OPTIONS request, but yet again, no dice. So I had to enable options requests on the services that I allow cross-domain access on until I find a better solution.

Software developer, building things with code in sunny Scottsdale, AZ.

Comments