You ever have one of those days where you fix something… and it still doesn’t work? That was me — a while ago, back when I was still learning the ropes of ASP.NET Core middleware. I enabled CORS in my app, confident and caffeinated — and still got blocked. I triple-checked everything. The headers? Correct. The origin? Allowed. The browser? Still angry.
This is the story of how one simple UseCors() misplacement cost me hours of debugging — and how I finally won.
The Problem
It started with a front-end request failing with the usual suspect:
“Access to fetch at [URL] from origin [another URL] has been blocked by CORS policy.”
No biggie, right? I had done this before. I added a CORS policy in my startup:
services.AddCors(options =>
{
options.AddPolicy("MyCorsPolicy", builder =>
{
builder.WithOrigins("https://myfrontend.example.com")
.WithMethods("GET", "POST")
.WithHeaders("Content-Type");
});
});
And then added:
app.UseCors("MyCorsPolicy");
…or so I thought.
The Solution
After hours of squinting at code and refreshing the browser like it owed me money, I finally saw it:
I had placed app.UseCors() after app.UseRouting() and app.UseAuthorization() in the middleware pipeline. That was the bug.
In ASP.NET Core, middleware order matters. I had enabled CORS — and still got blocked — because I told the app to allow it too late in the request pipeline.
The fix? Move app.UseCors() immediately after app.UseRouting(), before anything else touches the request.
A Deeper Dive
The ASP.NET Core middleware pipeline is like a conga line. If CORS isn’t in the right spot, it doesn’t get a chance to handle the preflight request properly.
The browser sends an OPTIONS request. If CORS hasn’t had its say by then, it’s game over. Silent fail. No warning. Just angry red console errors.
Even worse? No compiler error. No exception. Just a misbehaving app.
Best Practices
- Always place
app.UseCors()right afterapp.UseRouting(). - Use restrictive CORS policies — only allow the domains, methods, and headers you truly need.
- Never assume “it’s enabled, so it’s working.”
- Double-check middleware order — especially when dealing with security features.
- Keep your browser dev tools open — they tell the truth.
Conclusion
If you’ve ever felt like you “enabled CORS and still got blocked,” you’re not alone. This happened to me a long time ago, but it stuck with me as one of those early lessons you don’t forget.
Middleware ordering can be a sneaky culprit. But once you understand how the pipeline works, it becomes second nature.
We win some, we debug some. And every bug like this teaches us something. In this case: CORS doesn’t care what you meant — only what you coded.
Happy coding — and may your headers always align!





Leave a Reply