Reputation: 1261
I am having some trouble allowing cors. I have set server side
like so:
app.UseCors(builder => builder.WithOrigins("http://localhost:4200/").AllowAnyHeader());
Inside of the configure
method of the startup
class
When the my web API is hit, it will return the data fine.
However, the problem seems to be with Angular as in the I get the following error:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
Here is my angular web api call
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';;
@Injectable()
export class ProfileService {
private baseUrl = 'api/profile/';
constructor(private http: HttpClient) { }
getLookups(step: number) {
return this.http.get('http://localhost:51658/' + this.baseUrl + 'lookups/' + step)
}
}
Upvotes: 11
Views: 29732
Reputation: 1880
U can configure Cors service by adding default policy in ConfigureServices
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddDefaultPolicy(
builder =>
{
builder.WithOrigins("http://localhost:4200");
});
});
.... add other services
}
and don't forget to add UseCors
in Configure
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
.. other middlewares
app.UseCors();
app.UseRouting();
.. other middlewares
}
Upvotes: 1
Reputation: 619
The answer is correct but still, for some people, it might not work the reason is the placement of statements. You must write all CORS related statements before useMvc()/addMvc.
In Asp net Core. The syntax will look like
In ConfigureServices method
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200");
});
});
// make sure the cors statement is above AddMvc() method.
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
In the Configure method
app.UseCors(MyAllowSpecificOrigins);
// make sure cors is above add UseMvc method.
app.UseMvc();
Here MyAllowSpecificOrigins is just a policy name and you can define at the top of your class
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
I hope it helps.
Upvotes: 1
Reputation: 931
Am serving angular on other port like :4200 or :4300 depending on the number of ports in use
so I have configured my asp.net core app in
startup.cs
file to allow CORS from other sites
public class Startup
{
readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
var config = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.DestinationMemberNamingConvention = new LowerUnderscoreNamingConvention();
cfg.AddProfile(new ApplicationMappingProfile());
});
var mapper = config.CreateMapper();
services.AddSingleton(mapper);
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins,
builder =>
{
builder.WithOrigins("http://localhost:4200",
"http://localhost:4300")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
// Add EntityFramwork support for sqlServer
services.AddEntityFrameworkSqlServer();
//Add APplicationDbContext
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
//create a service scope to get an ApplicationDbcontext instance using DI
using (var serviceScope =
app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var dbContext =
serviceScope.ServiceProvider.GetService<ApplicationDbContext>();
//create the db if it doesn;t exist
dbContext.Database.Migrate();
DbSeeder.Seed(dbContext);
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseCors(MyAllowSpecificOrigins);
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
please read asp.net core documentation
Upvotes: -2
Reputation: 180
"WithOrigins" expect an array, not a string so maybe this is your case. However the minimum requirements for Cors to works in your case are:
In Startup.cs to add
services.AddCors();
before services.AddMvc();
and also:
string[] origins = new string[] { "http://localhost:4200" };
app.UseCors(b=>b.AllowAnyMethod().AllowAnyHeader().WithOrigins(origins));
Again add it before app.UseMvc(your routes ...)
Or what you actually need doesn't matter the technology is to add a "Access-Control-Allow-Origin" header with value the origin/origins in the response of the server which in .Net core 2 can be done like this (in any method in a controller):
ControllerContext.HttpContext
.Response
.Headers
.Add("Access-Control-Allow-Origin","http://localhost:4200");
or globally - you can create a middleware that add this header to all the responses when the origin match. Works also in Angular 6 and .Net Core 2 as separate applications.
Upvotes: 7
Reputation:
change your line in API with :
app.UseCors(builder => builder.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowAnyCredentials());
be sure you added Services.AddCors();
in ConfigureServices()
stop the server and run again after changes are made.
Upvotes: 17
Reputation: 1261
Changed builder.WithOrigins("http://localhost:4200/")
to
builder.WithOrigins("http://localhost:4200")
(Removed the '/')
Upvotes: 18
Reputation: 68635
Also try to add AllowAnyMethod
to the chain.
builder.WithOrigins("http://localhost:4200/").AllowAnyMethod().AllowAnyHeader()
Upvotes: 0