Enabling CORS in the ASP.NET Core application

CORS stands for Cross-Origin Resource Sharing, and it is restricted by browsers to prevent API requests across domains. For example, we have an SPA (Single-Page Application) running on a browser using a client-side framework like Angular or React to make calls to the Web APIs hosted on another domain, like my SPA site having a domain (mychapter8webapp.com) and accessing the APIs of another domain (appservices.com), which is restricted. Making calls to the services hosted on some other server and domain is restricted by browsers, and users will not be able to call those APIs. Enabling CORS on the server-side level addresses this problem.

To enable CORS in our ASP.NET Core project, we can add CORS support in the ConfigureServices method:

services.AddCors(); 

In the Configure method, we can use CORS by calling the UseCors method and defining the policies to allow cross-domain requests. The following code allows requests to be made from any header, origin, or method, and also allows us to pass credentials in the request header:

app.UseCors(config => { 
  config.AllowAnyHeader(); 
  config.AllowAnyMethod(); 
  config.AllowAnyOrigin(); 
  config.AllowCredentials(); 
});

The preceding code will allow CORS globally in the application. Alternatively, we can also define CORS policies and enable them on specific controllers depending on different scenarios.

The following table defines the basic terminology used in defining CORS:

Terminology

Description

Sample

Header

Request header allowed to be passed within the request

Content-Type, Accept, and so on

Method

HTTP verb of the request

GET, POST, DELETE, PUT, and so on

Origin

Domain or request URL

http://techframeworx.com

 

To define the policies, we can add a policy when adding CORS support in the ConfigureServices method. The following code shows two policies that have been defined while adding CORS support:

services.AddCors(config => 
{ 
  //Allow only HTTP GET Requests 
  config.AddPolicy("AllowOnlyGet", builder => 
  { 
    builder.AllowAnyHeader(); 
    builder.WithMethods("GET"); 
    builder.AllowAnyOrigin(); 
  }); 
 
  //Allow only those requests coming from techframeworx.com 
  config.AddPolicy("Techframeworx", builder => { 
    builder.AllowAnyHeader(); 
    builder.AllowAnyMethod(); 
    builder.WithOrigins("http://techframeworx.com"); 
  }); 
});

The  AllowOnlyGet policy will only allow requests that are making a GET request; the Techframeworx policy will only allow requests that are being made from techframeworx.com.

We can use these policies on Controllers and Actions by using the EnableCors attribute and specifying the name of the attribute:

[EnableCors("AllowOnlyGet")] 
public class SampleController : Controller 
{ 

 } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.156.176