Poul K. Sørensen
Poul K. Sørensen

Reputation: 17530

How to add CORS to only some requests in aspnet core

Currently, my app builder pipeline looks like

public void Configure(IApplicationBuilder app,
    Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
{
    app.MapWhen((ctx) =>
    {
        return ctx.Request.Host.Host == "api.example.com";
    }, innerbuilder =>
    {
        innerbuilder.UseCors("ApiCorsPolicy");
        app.UseMvc(); //This is for the api subdomain
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();

        // to do - wire in our HTTP endpoints
        app.Use(async(ctx, next) =>
        {
            if (Path.GetExtension(ctx.Request.Path) == ".ts" ||
                Path.GetExtension(ctx.Request.Path) == ".tsx")
            {
                await ctx.Response.WriteAsync(
                    File.ReadAllText(
                        ctx.Request.Path.Value.Substring(1)));
            }
            else
            {
                await next();
            }

        });
    }

    app.UseSignalR(routes =>
    {
        routes.MapHub<DataNotificationHub>("/hubs/notifications");
    });

    app.UseStaticFiles();
    app.UseMvc(); //This is for the webpage on www
}

I don't know if there is any downside to using two UseMvc and mapwhen?

but it seems redundant what I am doing and I was wondering if there are a better approach ?

Bassically the app is service both the "portal" and the "api" where api is under a subdomain api.example.com. Are there better ways to add CORS to only the api part? Maybe later something else is coming that i only want on the api.example.com hostname, is mapWhen the best option?

Upvotes: 1

Views: 201

Answers (1)

Poul K. S&#248;rensen
Poul K. S&#248;rensen

Reputation: 17530

I decided to split it up into two startup classes and then host them in two seperate processes. I did this due to it being easier to seperate/maintain in the long run.

Then i just created a dev startup that uses both for when developing locally.

public class ApiStartup
{
    public void ConfigureContainer(IUnityContainer container)
    {
        container.RegisterInstance("This string is displayed if container configured correctly",
                                   "This string is displayed if container configured correctly");

        CustomAuthStorageExtensions.Initialize();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(o => o.AddPolicy("ApiCorsPolicy", builder =>
        {
            builder.AllowAnyOrigin()
                   .AllowAnyMethod()
                   .AllowAnyHeader()
                   .SetPreflightMaxAge(TimeSpan.FromHours(1));
        }));


        IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
        };

        services.AddMvc(o =>
        {
            o.ModelBinderProviders.Insert(0, new RowModelBinderProvider());
        }).AddRazorPagesOptions(o =>
        {

        }).AddJsonOptions(o =>
        {

            o.SerializerSettings.Converters.Add(dateConverter);


        });


        services.AddSingleton(new MessageProcessorOptions
        {
            ConcurrentMessagesProcesses = 3,
            QueuePath = "earthml-pimeter",
            ListenerConnectionStringKey = "PimetrServiceBus",
        });
        services.AddTransient<IMessageHandler<StorageProviderMessage>, ProviderMessageHandler>();
        services.AddSingleton<IHostedService, ResourceProviderMessageProcessorHostedService>();

    }


    public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
    {
        app.UseCors("ApiCorsPolicy");
    }

}

public class PortalStartup
{
    public void ConfigureContainer(IUnityContainer container)
    {
        container.RegisterInstance("This string is displayed if container configured correctly",
                                   "This string is displayed if container configured correctly");

        CustomAuthStorageExtensions.Initialize();
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton(new CDNHelper());

        IsoDateTimeConverter dateConverter = new IsoDateTimeConverter
        {
            DateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.fff'Z'"
        };

        services.AddMvc();

        services.AddSignalR(o =>
        {

        }).AddJsonProtocol(j =>
        {
            j.PayloadSerializerSettings.Converters.Add(dateConverter);
        });

    }

    public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
    {

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();

            // to do - wire in our HTTP endpoints
            app.Use(async (ctx, next) =>
            {
                if (Path.GetExtension(ctx.Request.Path) == ".ts" || Path.GetExtension(ctx.Request.Path) == ".tsx")
                {

                    await ctx.Response.WriteAsync(File.ReadAllText(ctx.Request.Path.Value.Substring(1)));
                }
                else
                {
                    await next();
                }

            });
        }


        app.UseSignalR(routes =>
        {
            routes.MapHub<DataNotificationHub>("/hubs/notifications");
        });

        app.UseStaticFiles();

        app.UseMvc();
    }
}

public class DevStartup
{
    private PortalStartup PortalStartup = new PortalStartup();
    private ApiStartup ApiStartup = new ApiStartup();

    public void ConfigureContainer(IUnityContainer container)
    {
        ApiStartup.ConfigureContainer(container);
    }
    public void ConfigureServices(IServiceCollection services)
    {
        ApiStartup.ConfigureServices(services);
        PortalStartup.ConfigureServices(services);
    }

    public void Configure(IApplicationBuilder app, Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
    {
        PortalStartup.Configure(app, env);
    }

}

Upvotes: 1

Related Questions