0

I am using Asp.Net web API 2.0 with Angular 6 for UI. The solution contains the projects for angular and web API. My solution works fine (I am able to access pages and login) when I am running it on Visual Studio on localhost. However when I deploy the build on server I am unable to login and getting the below error:

Access to XMLHttpRequest at 'http://xx.xx.xx.xxx:xxxxx/authenticate' from origin 'http://xx.xx.xx.xxx:xxxxx' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

donatasj87
  • 760
  • 9
  • 23

3 Answers3

0

To quickly handle CORS for Web API, add below settings in web.config file of Web API inside <system.webServer> section:

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
    </customHeaders>
</httpProtocol>

But there is a security risk involved in enabling CORS. A good explanation is here.

as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
0

Can you please add this following code to startup.cs -> configure()

app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin().AllowCredentials());
0

Browser security prevents a web page from making AJAX requests to another domain. This restriction is called the same-origin policy and prevents a malicious site from reading sensitive data from another site. However, sometimes you might want to let other sites call your web API.

Install-Package Microsoft.AspNet.WebApi.Cors

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method: config.EnableCors();

Next, add the [EnableCors] attribute to the Controller class

[EnableCors(origins: "*", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }

Now you can access the API's

Shivam Mishra
  • 319
  • 3
  • 15