Hi @Manny ,
Thanks for reaching out.
I understand that you are trying to call protected web API through Web Application and getting CORS error.
This is due to when the two applications are hosted at different domains then browser security prevents a web page from making requests to another domain. This restriction is called the same-origin policy and prevents a malicious site from reading sensitive data from another site.
Cross Origin Resource Sharing(CORS) allows a server to relax the same-origin policy and allow cross domain calls.
For .Net Core application, Firstly, Install NuGet Package Manager to allow cross domains calls by enabling CORS in Web API which installs the latest package and updates all dependencies.
dotnet add package Microsoft.AspNet.WebApi.Cors
The easiest way to enable CORS to add following in code to the WebApiConfig.Register
EnableCorsAttribute cors = new EnableCorsAttribute(“”,””,””)*
*Config.EnableCors(cors);
Three parameters of EnableCorsAttribute such as:
Origin - Use the URI where you deployed the WebApp. This allows cross-origin requests from your WebApp only, while still disallowing all other cross-domain requests.
Headers - application/x-www-form-urlencoded, multipart/form-data, text/plain
Methods - GET, PUT, and POST methods calls are allowed. You can restrict GET calls only.
e.g EnableCorsAttribute(“http://webapp.net”,”*”,”GET”)
Other way to enable CORS attribute is to add [EnableCors] in controller class either to enable CORS at class level or method level as:
[EnableCors(origins: "http://webapp.net ", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
}
You can also disable CORS for an action, add the [DisableCors] attribute to the action which enables CORS for every method except that method.
There are other ways to enable CORS as well:
• In middleware using a named policy or default policy.
• Using endpoint routing.
We recommend using either [EnableCors] attribute or middleware, not both in the same application.
Hope this will help.
Thanks,
Shweta
Please remember to "Accept Answer" if answer helped you.