So here is the situation, I’m currently working on a website that has multiple environment but all share the same base domain.
As an example let’s say we have those:
Since I don’t want to share my domains with everyone by adding the CORS allowed origins directly from those, I want to my this dynamic for *.mydomain.com but without the wildcard.
First, you’ll need the Microsoft.AspNet.WebAPI.Cors package on NuGet.
You’ll need to add the following in your WebApiConfig.cs:
public static void Register(HttpConfiguration config)
However, that method allow us to set a custom policy. Like so:
public class MyCorsPolicy : ICorsPolicyProvider
public Task<CorsPolicy> GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken)
var policy = new CorsPolicy();
var requestUri = request.RequestUri;
var authority = requestUri.Authority.ToLowerInvariant();
if (authority.EndsWith(".mydomain.com") || authority == "mydomain.com")
// returns a url with scheme, host and port(if different than 80/443) without any path or querystring
var origin = requestUri.GetComponents(System.UriComponents.SchemeAndServer, System.UriFormat.SafeUnescaped);
So with that default policy, we allow anyone from a subdomain to make request to us without having to store a list of every subdomain that could contact us.
Of course, you could also set allowed methods, headers and such in this policy.