Sri
Sri

Reputation: 2328

CORS: No 'Access-Control-Allow-Origin' header is present on the requested resource. Angular, Net Core

I am using Angular, connecting to a Net Core web api. The angular part is hosted on firebase, and the net core web api is hosted on an IIS server. I am using https for both.

I am receiving the No 'Access-Control-Allow-Origin' error when trying to make a request.

In my ConfigureServices(), i have

services.AddCors(options =>
        {
            // this defines a CORS policy called "default"
            options.AddPolicy("default", policy =>
            {
                policy.AllowAnyOrigin()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
            });
        });

In my Configure(), I have app.UseCors("default")

app.UseCors("default");

In my controller, I have

[HttpGet]
    [Authorize]
    [EnableCors("default")]
    //GET : /api/UserProfile
    public async Task<Object> GetUserProfile()
    {
        string userId = User.Claims.First(c => c.Type == "UserID").Value;
        var user = await _userManager.FindByIdAsync(userId);
        return new
        {
            FullName = user.FullName,
            Email = user.Email,
            UserName = user.UserName
        };
    }

My angular request is as follows,

getUserProfile() {
        const httpOptions = {
          headers: new HttpHeaders({
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          })
        };
        return this.http.get(this.BaseURI + '/UserProfile', httpOptions);
      }

Can anyone explain why I am receiving this CORS error? My addMvc() and useMvc() functions are both written after the addCors() and useCors()

Upvotes: 2

Views: 7305

Answers (5)

mohammad Ali Feghhi
mohammad Ali Feghhi

Reputation: 19

Try this:

In Startup.cs, inside "ConfigureServices" method

services.AddCors(options =>
        {
            options.AddPolicy("default",
                builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyHeader()
                           .AllowAnyMethod()
                           .AllowCredentials()
                           .Build();
                });
        });

And then inside "Configure" method, write on top app.UseMvc();

app.UseCors("default");

And then in Program.cs

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
               .UseStartup<Startup>()
               .UseUrls("put your client side link here");
               //for example: "http://localhost:4200"

And then add this codes at the top of controller:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Produces("application/json")]

And then change your Action ("I mean GetUserProfile()") like this:

[HttpGet]
public async Task<IActionResult> GetUserProfile()
{
    var userId = user.Claims.First(c => c.Type.equals("UserID")).Value;
    var user = await _userManager.FindByIdAsync(userId);
    return Ok(new
    {
        FullName = user.FullName,
        Email = user.Email,
        UserName = user.UserName
    });
}

And about angular code try this:

getUserProfile() {
    const TOKEN = localStorage.getItem("token");
    const httpOptions = {
      headers: new HttpHeaders({
          "Authorization": "Bearer " + TOKEN,
          "Content-Type": "application/json"
      })
    };
    return this.http.get(this.BaseURI + '/UserProfile', httpOptions);
  }

Upvotes: 1

Sri
Sri

Reputation: 2328

I appreciate all the answers, however I have tried all the solutions and none worked. I am unsure why, but that is the case.

What did work, was setting Response Headers in my IIS. Adding the following to response headers Allow-Access-Control-Origin * fixed my issue.

I also had to create an IIS login for my SQL database but that is another issue.

Thank you everyone for your suggestions

Upvotes: 1

Nandan Sony
Nandan Sony

Reputation: 53

It will show the CORS policy error if route is not set. Try this:

[Authorize]
[EnableCors("default")]
//GET : /api/UserProfile
[HttpGet("GetUserProfile")]
public async Task<Object> GetUserProfile()
{
    string userId = User.Claims.First(c => c.Type == "UserID").Value;
    var user = await _userManager.FindByIdAsync(userId);
    return new
    {
        FullName = user.FullName,
        Email = user.Email,
        UserName = user.UserName
    };
}

Upvotes: 3

Jalpa Panchal
Jalpa Panchal

Reputation: 12749

Try to use the below code:

 services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder
                .AllowAnyMethod()
                .AllowCredentials()
                .SetIsOriginAllowed((host) => true)
                .AllowAnyHeader());
    });

and

app.UseCors("CorsPolicy");

Note: dont use app.UseCors() after app.UseMvc()

You could refer this below link for more detail:

Enable Cross-Origin Requests (CORS) in ASP.NET Core

If you still face an error then try to turn on exceptions/logging and diagnose what's causing the error in your web API.

asp net core - No 'Access-Control-Allow-Origin' header is present on the requested resource

Upvotes: 1

PabloM
PabloM

Reputation: 194

Try this:

In Startup.cs, inside ConfigureServices

services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader();
        }));

And inside Configure:

app.UseCors("MyPolicy");

Upvotes: 1

Related Questions