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
b. In the configure method, I added the following code
PS: This needs to come before the app.useMvc(); middleware call.
2. On every applicable controller, I decorated the controller class with the following
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"?>
<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" />
<aspNetCore processPath=”dotnet” arguments=”.\myprojetname.dll” stdoutLogEnabled=”false” stdoutLogFile=”.\logs\stdout” hostingModel=”OutOfProcess” />
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