Enable CORS

When accessing Web API from client applications, it restricts access to web resources unless they are being used from the same domain where the application is running. In the ASP.NET project, we can enable CORS (Cross Origin Resource Sharing), which allows a restricted resource to be accessible by any other domain where the client application is running. CORS in the ASP.NET project can be configured in several ways, and can specify Origin, Header, and Method, which we need to be allowed from external sources.

To enable CORS in ASP.NET MVC 6, we have to add a NuGet package, as follows: Microsoft.AspNetCore.Cors

We can configure CORS at the Controller, Action, or Middleware levels. To enable CORS, we have to first define the policies, and this can be done either in the ConfigureServices method or Configure method of the Startup class.

Here is an example of setting up CORS in the ConfigureServices method:

    services.AddCors(options => { 
options.AddPolicy("AllowLimited", builder =>
builder.WithHeaders("Content-Type", "Accept")
.WithMethods("GET", "POST").AllowAnyOrigin();
});

The preceding policy will allow only GET and POST requests, and each request should have a request header as Content-Type and Accept to accept requests from any domain as specified in origin.

To enable CORS at the Controller or Action level, we can specify the EnableCors attribute in the Controller class or Action method, and specify the policy as defined in the ConfigureServices method:

    [EnableCors("AllowLimited")] 
public class PersonController : Controller
{
}

And here is the example of adding EnableCors on the method level:

    [EnableCors("AllowLimited")] 
[HttpGet]
public IEnumerable<string> Get()
{
return lst;
}

To use CORS at the middleware level, we can call the UseCors method and specify the policy, as defined earlier.

    public void Configure(IApplicationBuilder app,
IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseCors("AllowLimited");
}
..................Content has been hidden....................

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