debug doesn't enter inside AddCors method

In startup.cs I have AddCors to services, I want to debug code from inside of AddCors, but Breackpoint doesn’t fire inside

 services.AddCors(options =>
            {
                //debug didn't fire here
                var corsOrigins = configuration["cors-origins"].Split(",");
                if ((corsOrigins.Length == 1)
                {
                    options.AddPolicy("CorsPolicy",
                        builder => builder.SetIsOriginAllowed(_ => true)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
                }
                else
                {
                    options.AddPolicy("CorsPolicy",
                        builder => builder.WithOrigins(corsOrigins)
                            .AllowAnyMethod()
                            .AllowAnyHeader()
                            .AllowCredentials());
                }
            });

any ideas how can I stop code execution inside AddCors method?

>Solution :

The options builder inside will be evaluated when a request comes into the API. This is essentially because the middleware receives an IOptions<CorsOptions> from the container and evaluates its .Value property.

We can simulate this. Imagine you’re building the container:

ServiceCollection services = new ServiceCollection();
services.AddCors(options =>
    {
        var corsOrigins = configuration["cors-origins"].Split(",");
        if ((corsOrigins.Length == 1)
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.SetIsOriginAllowed(_ => true)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
        }
        else
        {
            options.AddPolicy("CorsPolicy",
                builder => builder.WithOrigins(corsOrigins)
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
        }
    });

IServiceProvider provider = services.BuildServiceProvider();
CorsOptions options = provider.GetRequiredService<IOptions<CorsOptions>>().Value;

Obviously you can allow ASP.NET Core to build the services, etc. you just need access to the IServiceProvider somewhere to retrieve the options from the container. This should hit your breakpoint inside the lambda function, or let you directly check the resulting CorsOptions object.

Leave a Reply