Search code examples
asp.net-coremiddleware

How can I set Cross-Origin in ASP.NET Core?


I have a task about general-token. Each request comes from an IP, and I have to call WithOrigins in each request.

Actually I need an AddScoped service in a middleware.

Please help me


Solution

  • using Microsoft.AspNetCore.Cors.Infrastructure; 
    using Microsoft.AspNetCore.Http;
    
    public class CustomCorsPolicyProvider: ICorsPolicyProvider {
        public Task<CorsPolicy> GetPolicyAsync(HttpContext context,string policyName)
    {
        // Implement logic to select a policy based on the request
        // For example, you can vary the policy based on the request's origin, headers, etc.
    
        var corsPolicyBuilder = new CorsPolicyBuilder()
            .WithOrigins("http://example.com") // Replace with dynamic logic
            .AllowAnyMethod()
            .AllowAnyHeader();
    
        return Task.FromResult(corsPolicyBuilder.Build());
    } }
    

    then

    public void ConfigureServices(IServiceCollection services) {
        services.AddCors();
        services.AddSingleton<ICorsPolicyProvider, CustomCorsPolicyProvider>();
        // ... other services 
    }
    

    AND

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ... other configurations
    
        app.UseCors(); // Use the custom CORS policy provider
    
        // ... other middleware
    }