Created
May 27, 2022 20:38
-
-
Save yamgarcia/371ec072a6190e8173a154ad582a9e20 to your computer and use it in GitHub Desktop.
Access-Control-Allow-Origin Error solution - Alternative Cors Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Threading.Tasks; | |
using API.Data; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.HttpsPolicy; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.EntityFrameworkCore; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.Extensions.Logging; | |
using Microsoft.OpenApi.Models; | |
namespace API | |
{ | |
public class Startup | |
{ | |
private readonly IConfiguration _config; | |
public Startup(IConfiguration config) | |
{ | |
_config = config; | |
} | |
// public IConfiguration Configuration { get; } | |
// This method gets called by the runtime. Use this method to add services to the container. | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddDbContext<DataContext>(options => | |
{ | |
options.UseSqlite(_config.GetConnectionString("DefaultConnection")); | |
}); | |
services.AddControllers(); | |
// services.AddCors(); | |
services.AddCors(setup => | |
{ | |
setup.AddPolicy("AngularLocalPolicy", | |
config => { config.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod(); }); | |
}); | |
services.AddSwaggerGen(c => | |
{ | |
c.SwaggerDoc("v1", new OpenApiInfo { Title = "WebAPIv5", Version = "v1" }); | |
}); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
app.UseSwagger(); | |
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "WebAPIv5 v1")); | |
} | |
app.UseHttpsRedirection(); | |
app.UseRouting(); | |
// app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:4200/")); | |
app.UseCors("AngularLocalPolicy"); | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllers(); | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
THANK YOU!!!