Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

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.