Ask Your Question
2

How can ASP.NET Core 6 be configured to define a cors policy based on IP?

asked 2023-01-10 11:00:00 +0000

devzero gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-03-18 08:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-01-10 11:00:00 +0000

Seen: 1 times

Last updated: Mar 18 '22