HI WELCOME TO SIRIS

React js with Asp.net Web API – CRUD Operations part3

But there is a Problem – CORS

CORS (Cross-Origin Resource Sharing) : it is a mechanism to let a user agent (browser) gain permission to access selected resources from a server on a different origin (domain) than the site currently in use. cross-origin HTTP request occurs when it requests a resource from a different domain, protocol, or port than the one from which the current document originated.
In this application, our web API project will block request from React application, since they are cross-origin HTTP request(from different port numbers – 3000 and 28750). In-order to allow cross-origin HTTP request, we have to configure Web API project for this localhost:3000 request. so let’s look how we can do that.
First of we have to install NuGet Package : WebApi.Cors. Back to Visual Studio, Select your Web API project from solution explorer, then go to Tools > Library Package Manager > Package Manager Console. use following NuGet command to install WebApi.Cors.
NuGet Command for Web API Cors
Now let’s look how we can use this package. In-order allow cross-origin request in Web API controller Employee we can do this.
Here we have given permission for http request from ‘http://localhost:4200’, it’s not a good idea to add this EnableCors attribute for all Web API controlls if your project is big in size. In that case you do this.
Go to App_Start >WebApiConfig.cs file. add following lines of code
now web API project is ready for cross-origin request from our react application.
try to navigate this URL /api/Employee from your web API project some of you may get this problem.
Could not load file or assembly System.Web.Http
It is due to different version of WebApi.Cors (5.2.3) and System.Web.Http (5.0.0), so lets install same version of WebApi.Core (Not Cors it is Core). it will resolve this assembly problem. for that you can run following NuGet Command from Package Manager Console.
So here we have completed with Web APi Project. Back to React project.

Reactjs with Asp.net Web API – CRUD Operations part1