To define a CORS policy based on IP in ASP.NET Core 6, you can use the AddCors
method in the ConfigureServices
method of the Startup
class. Here is an example:
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(options =>
{
options.AddPolicy("AllowSpecificIPs", builder =>
{
builder.WithOrigins("http://192.168.1.1", "https://192.168.1.2")
.AllowAnyHeader()
.AllowAnyMethod();
});
});
// other configuration here
}
In this example, we define a CORS policy named AllowSpecificIPs
that allows requests from the IP addresses 192.168.1.1
and 192.168.1.2
. You can replace these IP addresses with the ones you want to allow. The policy allows any header and any HTTP method.
To use this policy in your controllers or actions, you can use the [EnableCors]
attribute and specify the policy name:
[EnableCors("AllowSpecificIPs")]
public class MyController : Controller
{
// actions here
}
This will enable CORS for all actions in the MyController
class, using the AllowSpecificIPs
policy we defined earlier.
Asked: 2023-01-10 11:00:00 +0000
Seen: 1 times
Last updated: Mar 18 '22