I have a asp.net core 3 application with Angular 8. So in Angular I have this method:
getValues() {
this.http.get('https://localhost:44323/api/Values/').subscribe(response => {
this.values = response;
}, error => {
console.log(error);
});
}
And my cs file looks like this:
public class Startup
{
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)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));
services.AddCors();
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors(x => x.WithOrigins().AllowAnyMethod().AllowAnyHeader());
}
}
So I am doing the UseCors thing. But I still get this error:
Access to XMLHttpRequest at 'https://localhost:44323/api/Values/' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Of course I googled this error. THat is why I have used the UseCors thing. But is what they recommonded. But I still get this error.
So I am stuck. Will be nice if somebody can tell me what I do wrong.
Thank you
I have it now like this:
[EnableCors("AllowOrigin")]
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
private protected DataContext _dataContext;
public ValuesController( DataContext dataContext)
{
this._dataContext = dataContext;
}
// GET api/values
[HttpGet]
[EnableCors("AllowOrigin")]
public async Task <IActionResult> GetValues()
{
var values = await _dataContext.Values.ToListAsync();
return Ok(values);
}
// GET api/values/5
[HttpGet("{id}")]
public async Task <IActionResult> GetValue(int id)
{
var value = await _dataContext.Values.FirstOrDefaultAsync(x => x.Id == id);
return Ok(value);
}
// POST api/values
[HttpPost]
public void Post([FromBody] string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
and this:
public class Startup
{
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)
{
string connectionString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(connectionString));
services.AddCors();
//services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
//app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseCors(x => x.WithOrigins("https://localhost:44323").AllowAnyHeader().AllowAnyMethod().AllowCredentials());
}
}
But then I will get this error:
An unhandled exception occurred while processing the request.
InvalidOperationException: Endpoint DatingApp.API.Controllers.ValuesController.GetValues (DatingApp.API) contains CORS metadata, but a middleware was not found that supports CORS.
Configure your application startup by adding app.UseCors() inside the call to Configure(..) in the application startup code.
Microsoft.AspNetCore.Routing.EndpointMiddleware.ThrowMissingCorsMiddlewareException(Endpoint endpoint)