Код: Выделить всё
public static class CorsExtensions
{
/**
* appsettings.json configuration
*
* CorsPolicy:{
* "PolicyName": "",
* "AllowedHosts": "*",
* "AllowedOrigins": "http://localhost:4200",
* "AllowedHeaders": "content-type",
* "AllowedMethods": "GET,POST,PUT,DELETE"
* }
*/
public static IServiceCollection ConfigureCors(this IServiceCollection services) where T: class
{
var configuration = services.BuildServiceProvider().GetService();
var corsPolicy = services.Configure(configuration!.GetSection("CorsPolicy"));
services.AddCors(options =>
{
options.AddPolicy(name: corsPolicy.PolicyName,
policy => policy.WithOrigins(corsPolicy.AllowedOrigins)
.AllowCredentials()
.WithHeaders(corsPolicy.AllowedHeaders)
.WithMethods(corsPolicy.AllowedMethods)
);
});
return services;
}
public static WebApplication AddCorsMiddleware(this WebApplication app)
{
app.UseCors(T.PolicyName);
return app;
}
}
Код: Выделить всё
builder.Services.ConfigureCors();
public class CorsPolicy
{
public string PolicyName { get; set; }
public string AllowedHosts { get; set; }
public string AllowedMethods { get; set; }
public string AllowedHeaders { get; set; }
public string AllowedOrigins { get; set; }
}
Как я могу написать метод расширения для динамического прочитайте свойства и настройте соответствующим образом.
Подробнее здесь: https://stackoverflow.com/questions/791 ... ion-method
Мобильная версия