CORS ON IIS AND .NET CORE WEB API — HOW I SOLVED IT

Oliver Johnson
2 min readMar 11, 2021

--

Recently I found myself needing to deploy an on premise dotnet core API to IIS.

Deploying on cloud services like Azure App Service — setting CORS is as simple as going to your portal settings and enabling the specific domains — or in most cases adding * to allow All.

It was a rude shock to me after I deployed the API on-premise and the frontend SPAs couldn’t access it due to CORS wahala (yeah — Nigerian speak for trouble).

After about 2 days of battling with this, this is how I solved it.

1. I made the following modifications to the startup.cs file

a. In configureservices method, I added the following code snippets

“services.AddCors(options =>

{

options.AddPolicy(“AllowAllHeaders”,

builder =>

{

builder.AllowAnyOrigin()

.AllowAnyHeader()

.AllowAnyMethod()

.AllowCredentials();

});

}); ”

b. In the configure method, I added the following code

“ app.UseCors(“AllowAllHeaders”);”

PS: This needs to come before the app.useMvc(); middleware call.

2. On every applicable controller, I decorated the controller class with the following

[EnableCors(“AllowAllHeaders”)]

3. On the IIS side — there are few changes to make this work

a. Added a web.config file with the following entries

<?xml version=”1.0" encoding=”utf-8"?>

<configuration>

<system.webServer>

<handlers>

<add name=”aspNetCore” path=”*” verb=”*” modules=”AspNetCoreModuleV2" resourceType=”Unspecified” />

<remove name=”ExtensionlessUrlHandler-Integrated-4.0" />

<remove name=”OPTIONSVerbHandler” />

<add name=”ExtensionlessUrlHandler-Integrated-4.0" path=”*.” verb=”*” type=”System.Web.Handlers.TransferRequestHandler” preCondition=”integratedMode,runtimeVersionv4.0" />

</handlers>

<aspNetCore processPath=”dotnet” arguments=”.\myprojetname.dll” stdoutLogEnabled=”false” stdoutLogFile=”.\logs\stdout” hostingModel=”OutOfProcess” />

</system.webServer>

</configuration>

To understand more about why this works, you can read further here: https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-5.0

And

Here: https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

--

--

Oliver Johnson
Oliver Johnson

Written by Oliver Johnson

Software Engineer with a bias for open and standards based system.I think,build and think again.I’m always trying, never afraid to fail.@oliverdejohnson

No responses yet