skip to Main Content

I just containerized a .NET 8 Azure Functions app. It works, but I can’t make CORS work.

// Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using MongoDB.Driver;
using APIs.Services.Azure.Storage.Queue;
using APIs.Services.Cache;
using APIs.Services.DocumentDB.Repositories;
using APIs.Services.MongoDB.Repositories;
using APIs.Services.User;
using APIs.Services.Logzio;
using APIs.Services.IPFS;
using APIs.Services.Midjourney;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;

var host = new HostBuilder()
    .ConfigureFunctionsWebApplication()
    .ConfigureServices((hostContext, services) =>
    {

        IConfiguration config = hostContext.Configuration;

        services.AddSingleton<ICachingService, CachingService>();
        // I also add other services here

        // CORS
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAll",
                builder =>
                {
                    builder
                        .AllowAnyOrigin()
                        .AllowAnyMethod()
                        .AllowAnyHeader()
                        .AllowCredentials();
                });
        });
    })
    .ConfigureWebHostDefaults(webBuilder =>
    {
        webBuilder.ConfigureKestrel(serverOptions =>
        {
            serverOptions.ListenAnyIP(5000); // Change to the desired port
        })
        .Configure((context, app) =>
        {
            // Use the CORS policy
            app.UseCors("AllowAll");
        });
    })
    .Build();

host.Run();

and

//host.json
{
  "version": "2.0",
  "extensions": {
    "queues": {
      "maxPollingInterval": "00:00:05",
      "visibilityTimeout": "00:00:30",
      "batchSize": 1,
      "newBatchThreshold": 0,
      "maxDequeueCount": 1
    },
    "maxConcurrentActivityFunctions": 1,
    "maxConcurrentOrchestratorFunctions": 1
  },
  "http": {
    "routePrefix": "",
    "cors": {
      "allowedOrigins": [
        "*"
      ],
      "allowedMethods": [
        "*"
      ],
      "allowedHeaders": [
        "*"
      ]
    }
  },
  "logging": {
    "applicationInsights": {
      "samplingSettings": {
        "isEnabled": true,
        "excludedTypes": "Request"
      }
    }
  }
}

Then I build the image and create the container.

If I go to the app url, I can see the Your Functions 4.0 app is up and running message.

But when I’m trying to use the API from my frontend app, I get CORS error

Access to XMLHttpRequest at 'http://host.docker.internal:7171/api/wallet' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

2

Answers


  1. Did you try adding origin URL in API >> CORS setting of your azure function as below?

    CORS Settings MSDN

    Login or Signup to reply.
  2. AllowAnyOrigin() and AllowCredentials() cannot be used together.

    To resolve the issue with CORS, remove AllowCredentials() in your code.

     builder =>
                    {
                        builder
                            .AllowAnyOrigin()
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                    });
    

    If you want AllowCredentials() and AllowAnyOrigin() together, you can use SetIsOriginAllowed(origin=>true) as mentioned in SO answer by @Konstantin Nikolskii.

    services.AddCors(options =>
    {
        options.AddPolicy("AllowAll", builder =>
            builder.SetIsOriginAllowed(origin => true)
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });
    
    • Use below code to allow access to the specific origin:
    services.AddCors(options =>
    {
        options.AddPolicy("withorigin",builder => builder
        .WithOrigins("https://example.com")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
    });
    

    I have created a .NET8.0 Isolated Azure function and enabled CORS with below code:

    Program.cs:

    var host = new HostBuilder()
        .ConfigureFunctionsWebApplication()
        .ConfigureServices(services =>
        {
            services.AddApplicationInsightsTelemetryWorkerService();
            services.ConfigureFunctionsApplicationInsights();
             services.AddCors(options =>
     {
         options.AddPolicy("CorsPolicy", builder =>
             builder.SetIsOriginAllowed(origin => true)
             .AllowAnyMethod()
             .AllowAnyHeader()
             .AllowCredentials());
         });
    })
        .Build();
    
    host.Run();
    

    Deployed to Azure:

    enter image description here

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search