Home > front end >  debug doesn't enter inside AddCors method
debug doesn't enter inside AddCors method

Time:06-14

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?

CodePudding user response:

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.

CodePudding user response:

Because AddCors is a method from a compiled assembly without a debug info and you can't debug inside of such assemblies without special tools. Without the tools the easiest way would be to get a source code for asp.net core and add it to your solution.

  • Related