Here is my program.cs class:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<IUserService, UserService>();
builder.Services.AddTransient<IUserRepository, UserRepository>();
#region IAUECManager Database Connection
builder.Services.AddDbContext<IAUECManagerDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("IAUECManagerConnectionString"));
});
#endregion
#region JWT Authentication
//TODO Change JWT Secret Key
var jwtSecretKey = "something that should be change in the future";
builder.Services.AddHttpClient();
builder.Services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(option =>
{
option.RequireHttpsMetadata = false;
option.SaveToken = true;
option.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtSecretKey)),
ValidateIssuer = false,
ValidateAudience = false
};
});
#endregion
//services.AddCors();
builder.Services.AddCors(o => o.AddPolicy("MyPolicy", builder => {
builder.AllowAnyHeader()
.AllowAnyMethod()
.AllowAnyOrigin();
}));
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseCors("MyPolicy");
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
Why when I want to send a request from ajax which is in my UI project that is including in the same solution with my api project it says:
Access to XMLHttpRequest at 'https://localhost:7039/api/V1/Users/Register' from origin 'https://localhost:44323' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.