CORS on asp.net core web api doesn't work after deploy on IIS [Answered]RSS

1 reply

Last post Feb 05, 2020 02:33 PM by Teoz82

  • CORS on asp.net core web api doesn't work after deploy on IIS

    Feb 05, 2020 09:46 AM|Teoz82|LINK

    I'm developing a net core webapi with an angular front end and a custom BasicAuthenticationHandler. When i debugging (i debug using "Visual studio code" not "Visual studio") everything works fine, now that i had deploying the web abi on IIS I can't make it works, it gives me CORS error: "...No 'Access-Control-Allow-Origin' header is present on the requested resource."

    Here is the code to enable CORS on web api:

    public void ConfigureServices(IServiceCollection services)
    {
    ...
        services.AddCors();
    
    ...
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
    ...
        app.UseCors(x => x
            .AllowAnyOrigin()
            .AllowAnyMethod()
            .AllowAnyHeader());

    I use this guide for setting IIS website:

    https://docs.microsoft.com/en-gb/aspnet/core/host-and-deploy/iis/index?view=aspnetcore-3.1

     i even create a controller method with 

    [AllowAnonymous]

    if I open the url thru browser, it gives me error 400, 401.1 if I use Postman, CORS error on angular app.

  • Re: CORS on asp.net core web api doesn't work after deploy on IIS

    Feb 05, 2020 02:33 PM|Teoz82|LINK

    I finally managed to solve the problem: I had enabled "Basic Authentication" on IIS because I mistakenly thought it was the right things to do.

    I found that IIS "Basic authentication" is different from what I had implemented (I created a custom "BasicAuthenticationHandler" that read headers e validate users)

    The problem was that IIS (or Angular, or Chrome, i don't know) instead of returning error "401 unauthorized" gave me CORS error even if "Anonymous authentication" was enabled (it's mandatory to disable all other authentications).