'CORS Response Header (Intermittently) not being returned in IIS - dotnet Web API on IIS 10
I scrape websites for data and then post it to a c# .NET 6.0 to a IIS server running 10.0.17763.1. After some RANDOM amount of time by post is being rejected by CORS with the following message,
Access to fetch at '{myUrl' from origin 'theirUrl' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
The script I am using is
setTimeout(function() {fetch('myEndpointUrl', {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/json'
},
body: JSON.stringify(
{
portURL: window.location.href,
portNumber: window.location.href,
portName: document.getElementsByClassName("MuiGrid-root MuiGrid-item MuiGrid-grid-sm-true")[0].textContent
}
The Program.cs is the following
using Kinetics.DatabaseContext;
using Kinetics.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.Configuration;
using Microsoft.AspNetCore.Cors;
using System.Web.Http;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
//cors
var devCorsPolicy = "devCorsPolicy";
builder.Services.AddCors(options =>
{
options.AddPolicy(devCorsPolicy, builder => {
//builder.WithOrigins("http://localhost:800").AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
//builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost");
//builder.SetIsOriginAllowed(origin => true);
});
});
// registers dbcontext
builder.Services.AddDbContext<KineticsDataContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("sqlConnection"));
});
var app = builder.Build();
app.UseCors(devCorsPolicy);
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
}
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
