Skip to content
Stef Heyenrath edited this page Jan 6, 2022 · 3 revisions

Issue

When calling WireMock.Net Server from a frontend applicatie (React / Angular), a CORS error is returned:

Cross-Origin Request Blocked: 
The Same Origin Policy disallows reading the remote resource at http://localhost:9091/__admin/mappings.
(Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200.

Solution

Cors support is not enabled by default, you can enable it yourself when configuring WireMock.Net Server, like:

var settings = new WireMockServerSettings
{
   // Other settings
};

/* Enable Cors */
var policyName = "MyPolicy";
settings.AdditionalServiceRegistration = services =>
{
    services.AddCors(corsOptions =>
        corsOptions.AddPolicy(policyName, // ◀️ MyPolicy
            corsPolicyBuilder =>
            {
                corsPolicyBuilder
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                    .AllowAnyOrigin();
            }));

    settings.Logger.Debug("Enable Cors");
};

/* Use Cors */
settings.PreWireMockMiddlewareInit = app =>
{
    var appBuilder = (IApplicationBuilder)app;
    appBuilder.UseCors(policyName); // ◀️ MyPolicy

    settings.Logger.Debug("Use Cors");
};

// Start Server
var server = WireMockServer.Start(settings);

See also WireMock.Net.StandAlone.NETCoreApp/Program.cs.

📚 References

Clone this wiki locally