alistair-c
1/14/2018 - 2:56 PM

Improved ASP.NET Startup code

public static class StartupExtensions
    {
        public static IMvcCoreBuilder AddMvcServices(this IServiceCollection services)
        {
            return services.AddMvcCore(opts =>
            {
                opts.AddFormatterMappings();
            })
            .AddJsonOptions(j =>
            {
                j.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            })
            .AddJsonFormatters()
            .AddApiExplorer()
            .AddDataAnnotations();
        }

        public static MvcOptions AddFormatterMappings(this MvcOptions opts)
        {
            opts.FormatterMappings.SetMediaTypeMappingForFormat("xml", "application/xml");
            opts.FormatterMappings.SetMediaTypeMappingForFormat("json", "application/json");
            return opts;
        }

        public static IApplicationBuilder UseWildcardCorsPolicy(this IApplicationBuilder app)
        {
            app.UseCors(c =>
                c.AllowAnyHeader()
                .AllowAnyMethod()
                .AllowAnyOrigin()
                .AllowCredentials());
            return app;
        }
    }
public static IWebHost BuildWebHost(string[] args) =>
            new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseDefaultServiceProvider((ctx, opts) => { })
                // .ConfigureServices(s => { s.AddTransient<IConfigureOptions<KestrelServerOptions>, KestrelServerOptionsSetup>(); })
                .ConfigureAppConfiguration(args)
                .ConfigureLogging()
                .UseStartup<Startup>()
                .Build();