My Situation
I constantly find myself provisioning new projects of all types (I’m probably not alone in this). I love that part - it’s like being a kid opening presents. The part that isn’t fun is getting tooling functioning so you can jump into your domain. I will admit, I do the same thing over and over which is literal insanity.
In this case, here is what I was using:
- VueJS: Provisioned from Vue/CLI
- ASP.NET Core 3 Web Api: Provisioned from .NET Core 3 SDK cli
Both were containerized and I was using Compose to spin them up. In dev, I was running over http so in this case the frontend was localhost:8080 and the backend was localhost:54132. Postman works fine but the browser blocks the call. Okay, here we go:
Problem
You have a frontend project pointing towards an ASP.NET Core web api project and keep getting No 'Access-Control-Allow-Origin'
errors. You debug or check your api logs and find the endpoint works fine but the frontend doesn’t get the correct header information.
Check this first!
I won’t lie. I do this all the time. I get so used to these tools just working that I forget about order of operations. If you add a CORS policy as a blanket - meaning you don’t have to specify CORS policies per endpoint (there are a few different ways check this out: ASP.NET Core Docs ), then you have to make sure that middleware runs first. Check this out:
In Startup.cs, you can specify a policy in ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy", builder =>
{
builder
.WithOrigins("http://localhost:8080")
.AllowAnyMethod()
.AllowAnyHeader();
});
});
services.AddControllers();
Make sure it happens before AddControllers()
.
Further down, you have to load UseCors()
before specifying UseEndpoints()
:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
In MVC, I think think was called UseMVC()
or something close to that.
That’s it!
Summary
I banged my head against this as it didn’t make sense to me. Unfortunately, I had app.UseCors("CorsPolicy");
at the end after UseEndpoints()
. Fortunately, I couldn’t find someone actually specifying this although tons of these types of frustrations existed between Stack Overflow and frontend forums so I get to document it to (hopefully) help someone else!
If this helped you out, tweet me @bitobrian.
If you’re interested in the project I was working on, here it is: https://github.com/bitobrian/titan-lite-vuewebapi