Interview Question
Qus: How can cross-origin requests with Dotnet Core be explained?
Answers (2)
To setup the CORS we need to go with the following steps
• Install Nuget package: Microsoft.AspNetCore.Cors.
For the installation we have 2 way to do it.
Using package manager,
PM> Install-package Microsoft.AspNetCore.Cors
Using application Nuget search.
• Configure CORS startup class inside the ConfigureService method.
public void ConfigureServices(IServiceCollection services)
services.AddCors(options =>
{
options.AddPolicy("Policy11",
builder =>builder.WithOrigins("http://hello.com"));
});
• Enable CORS using middleware in the Configure method.
public void Configure(IApplicationBuilder app)
{
app.UseCors("AllowMyOrigin");
}
• To enable CORS there are three ways to do so:
1. Middleware using a named policy or default policy.
2. Using endpoint routing.
3. Using [EnableCors] attribute.
Middleware uses a named policy or default policy.
public class Startup {
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddDefaultPolicy(builder => {
builder.WithOrigins("http://hello.com", "http://www.test.com");
});
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors();
app.UseEndpoints(endpoints => {
endpoints.MapControllers();
});
}
}
Using endpoint routing, CORS can be apply per-endpoint basis using the RequireCors.
public class Startup {
readonly string allowCors = "_myOrigins";
public void ConfigureServices(IServiceCollection services) {
services.AddCors(options => {
options.AddPolicy(name: allowCors, builder => {
builder.WithOrigins("http://hello.com");
});
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseCors();
app.UseAuthorization();
app.UseEndpoints(endpoints => {
endpoints.MapGet("/foo", context => context.Response.WriteAsync("foo")).RequireCors(MyAllowSpecificOrigins);
});
}
}
This [EnableCors] attribute allow CORS for selected endpoints, so it will not impact the all endpoints,
This attribute will be applied on the following places:
• Global
• Controller
• action method
Action Level –
public class TestController: ControllerBase {
[EnableCors("Policy2")]
[HttpGet]
public ActionResult>Get() {
return new string[] {
"apple",
"mango"
};
}
[EnableCors("Policy1")]
[HttpGet("{id}")]
public ActionResult< string >Get(int id) {
return "test"
}
Controller Level –
[EnableCors("Policy1")]
public class HomeController : Controller
{
}
Global Level –
public void ConfigureServices(IServiceCollection services) {
services.AddMvc();
services.Configure (options => {
options.Filters.Add(new CorsAuthorizationFilterFactory("Policy1"));
});
}