Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling CORS in .net core Web api and angular 6

Here I'm using an HTTP POST request from Angular 6 and it is hitting in the .net core Web API call, but I'm not getting the response output back to Angular 6 and in console got an error that:

"Access to XMLHttpRequest at 'http://localhost:55654/api/login/auth' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

But I'm a bit confused that if it is any CORS enabling access issue, it won't hit the web API call. But it hits the API call and I'm not getting the response back.

Angular 6 HTTP POST request:

this.http.post("http://localhost:55654/api/login/auth", credentials, {
  headers: new HttpHeaders({
 "Content-Type": "application/json"
      })
  }).subscribe(response => {
      let token = (<any>response);
      localStorage.setItem("jwt", token);
    }, err => {

    });

I've enabled the CORS in following methods in .NetCore Web API

Configure Method in Startup.cs:

...
app.UseCors(options =>
  options.WithOrigins("http://localhost:4200")
    .AllowAnyMethod()
    .AllowAnyHeader());
 ...

ConfigureServices Method in Startup.cs:

...
services.AddCors();
...
like image 401
Haritha Es Avatar asked Dec 31 '22 23:12

Haritha Es


2 Answers

On Startup.cs add in ConfigureServices:

services.AddCors();

On Configure add

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

This solved your problem

like image 197
PawelC Avatar answered Jan 12 '23 03:01

PawelC


As mentioned in the comments:

The call to app.UseMvc needs to be AFTER app.UseCors

...
app.UseCors(options =>
  options.WithOrigins("http://localhost:4200")
    .AllowAnyMethod()
    .AllowAnyHeader());

app.UseMvc();
...
like image 20
UncleDave Avatar answered Jan 12 '23 01:01

UncleDave