CORS issue
See original GitHub issueI am getting a cors issue, when I am calling my API from the client-side (Using React.js).
This the error as I am getting when I am calling my API from the frontend.
Access to XMLHttpRequest at 'https://myapi.io/bsp/createBlobEntry' from origin 'http://localhost:5000' 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.
In my startup.cs file
This is my ConfigureServices method.
public void ConfigureServices(IServiceCollection services)
{
// ********************
// Setup CORS
// ********************
services.AddCors(options =>
{
options.AddPolicy(MyAllowSpecificOrigins, builder => builder
.WithOrigins(
"http://localhost:5000",
"https://localhost:5000"
)
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials()
);
});
services.AddControllers(s =>
{
s.ReturnHttpNotAcceptable = true;
}).AddNewtonsoftJson(setupAction =>
{
setupAction.SerializerSettings.ContractResolver =
new CamelCasePropertyNamesContractResolver();
});
services.AddControllersWithViews();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo
{
Title = "Flash Multi Record Inquiry Subscriber",
Version = "v1",
Description = "Subscriber to Handle Multiple Search Queries"
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
c.IncludeXmlComments(xmlPath);
});
var mappingConfig = new MapperConfiguration(mc =>
{
mc.AddProfile(new MapperProfile());
});
services.Configure<BspClientConfig>(options =>
Configuration.GetSection("BspClient").Bind(options));
services.Configure<FhaClientConfig>(options =>
Configuration.GetSection("FhaClient").Bind(options));
services.Configure<ServiceBusProcessQueueConfig>(options =>
Configuration.GetSection("ServiceBusProcessQueue").Bind(options));
services.Configure<ServiceBusRetryQueueConfig>(options =>
Configuration.GetSection("ServiceBusRetryQueue").Bind(options));
services.Configure<MriDbConfig>(options =>
Configuration.GetSection("MRIDatabase").Bind(options));
services.Configure<AzureSqlAuthConfig>(options =>
Configuration.GetSection("AzureSqlAuth").Bind(options));
services.Configure<RetryMechanismConfig>(options =>
Configuration.GetSection("RetryMechanism").Bind(options));
var mapper = mappingConfig.CreateMapper();
var queueClient = CreateQueueClient();
services.AddHealthChecks();
services.AddSingleton(mapper);
services.AddSingleton(queueClient);
services.AddSingleton<IHealthCheckService, HealthCheckService>();
services.AddSingleton<IProcessQueueReader, ProcessQueueReader>();
services.AddSingleton<IProcessQueueWriter, ProcessQueueWriter>();
services.AddSingleton<IRetryQueueWriter, RetryQueueWriter>();
services.AddSingleton<IBspClient, BspClient>();
services.AddSingleton<IBspLoanProcessor, BspLoanProcessor>();
services.AddSingleton<ICaqLoanProcessor, CaqLoanProcessor>();
services.AddSingleton<ICavLoanProcessor, CavLoanProcessor>();
services.AddSingleton<IFhaClient, FhaClient>();
services.AddSingleton<IAzureADTokenProvider, AzureADTokenProvider>();
test(services);
services.AddSingleton<ITransactionRepository, TransactionRepository>();
services.AddSingleton<IBspRepository, BspRepository>();
}
and This is my configure method
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IProcessQueueReader queueReader)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors(MyAllowSpecificOrigins);
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseHealthChecks("/health");
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseSwagger(c => { c.SerializeAsV2 = true; });
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("/swagger/v1/swagger.json", "Flash Multi Record Inquiry Subscriber");
c.DocumentTitle = "Flash Multi Record Inquiry Subscriber";
});
queueReader.ProcessQueueMessages();
}
Like after seeing many forums. I also added the enable-cors attribute
[ApiController]
[Route("bsp")]
[EnableCors(origins: "http://localhost:5000", headers: "*", methods: "*")]
public class BspDataController : ControllerBase
Please help me to resolve this issue
Issue Analytics
- State:
- Created 3 years ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
CORS errors - HTTP - MDN Web Docs - Mozilla
If the CORS configuration isn't setup correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same ...
Read more >Understanding and Resolving CORS Error
The CORS behavior, commonly termed as CORS error, is a mechanism to restrict users from accessing shared resources. This is not an error...
Read more >3 Ways to Fix the CORS Error — and How the Access- ...
The error stems from a security mechanism that browsers implement called the same-origin policy. The same-origin policy fights one of the most ...
Read more >What Is a CORS Error and How to Fix It (3 Ways)
As a CORS error occurs when the external API server doesn't return the HTTP headers required by the CORS standard, you can add...
Read more >CORS Errors: Cross-Origin Resource Sharing
CORS errors happen in web apps if requests are made and servers don't return required headers. Read about Cross-Origin Resource Sharing in Ionic ......
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
You need to put CORS middleware after
app.UseRouting()
and beforeapp.UseEndpoints(...)
CORS with named policy and middleware
Thank you for contacting us. Due to a lack of activity on this discussion issue we’re closing it in an effort to keep our backlog clean. If you believe there is a concern related to the ASP.NET Core framework, which hasn’t been addressed yet, please file a new issue.
This issue will be locked after 30 more days of inactivity. If you still wish to discuss this subject after then, please create a new issue!