I’m building a C# application for which i have to update in database and that needs to make requests to an API running on a different domain. However, when I try to make these requests, I’m getting CORS errors.
I’ve read about CORS and understand that it’s a security feature that browsers use to prevent cross-domain requests, but I’m not sure how to enable it in my C# application.
Can someone please explain how to enable CORS in a C# application and provide an example of how to make a cross-domain request using CORS? Thanks in advance!
I had tried to install "Microsoft.AspNetCore.Cors" from package manager but is not working.
3
Answers
Copy And Paste In Program.cs
Then write this, also in Program.cs. But write it in the correct order, after
app.UseRouting();
and beforeapp.UseAuthentication();
– https://learn.microsoft.com/en-us/aspnet/core/fundamentals/middleware/?view=aspnetcore-7.0#middleware-orderusing (var client = new HttpClient())
In C# MVC application we can add Microsoft.AspNet.WebApi.Cors NuGet package. After successfully installing this package use the below line in a controller,
And, EnableCORS before defining APIs like: