Skip to content

Commit

Permalink
refactor: moved cors to web app builder extension
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaxelr committed May 6, 2024
1 parent 72c35c4 commit 5318776
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 14 deletions.
33 changes: 33 additions & 0 deletions src/Extensions/WebApplicationBuilder/Cors.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;

namespace Email.Extensions;

public static class CorsExtension
{
private const string Policy = "DefaultPolicy";

public static WebApplicationBuilder AddCors(this WebApplicationBuilder builder)
{
builder.Services.AddCors(options =>
{
options.AddPolicy(Policy,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});

return builder;
}

public static WebApplication UseCors(this WebApplication app)
{
app.UseCors(Policy);

return app;
}
}
19 changes: 5 additions & 14 deletions src/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Threading.Tasks;
using Carter;
using Carter.OpenApi;
using Email.Extensions;
using Email.Models;
using Email.Repositories;
using Microsoft.AspNetCore.Builder;
Expand All @@ -17,7 +18,7 @@
using Serilog;

const string ServiceName = "Email Service";
const string Policy = "DefaultPolicy";


var builder = WebApplication.CreateBuilder(args);

Expand All @@ -30,17 +31,7 @@

builder.Configuration.GetSection(nameof(AppSettings)).Bind(settings);

builder.Services.AddCors(options =>
{
options.AddPolicy(Policy,
builder =>
{
builder
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
});
});
builder.AddCors();

//Swagger
builder.Services.AddEndpointsApiExplorer();
Expand Down Expand Up @@ -69,7 +60,7 @@

builder.Services.AddSingleton(builder =>
{
return Polly.Policy.Handle<Exception>().WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
return Policy.Handle<Exception>().WaitAndRetry(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)));
});

builder.Services.AddSingleton(settings); //typeof(AppSettings)
Expand All @@ -80,7 +71,7 @@

var app = builder.Build();

app.UseCors(Policy);
app.UseCors();

if (builder.Environment.IsDevelopment())
{
Expand Down

0 comments on commit 5318776

Please sign in to comment.