Configure cors to allow all subdomains using ASP.NET Core (Asp.net 5, MVC6, VNext)

后端 未结 4 1654
甜味超标
甜味超标 2020-12-10 00:51

I have cors setup correctly in an ASP.NET Core web app. Im using the following package...

\"Microsoft.AspNet.Cors\": \"6.0.0-rc1-final\"

an

4条回答
  •  隐瞒了意图╮
    2020-12-10 01:25

    The out-of-the-box CorsService uses policy.Origins.Contains(origin) to evaluate a request. So, it does not look like there is a trivial way to do what you require, because the List must contain the origin. You could implement your own ICorsService, inherit what the out-of-the-box CorsService already provides, and tweak the methods to handle the *.mydomain.com wildcard.

    Edit Here is what I accomplished using yo aspnet to generate a 1.0.0-rc1-update2 Web Api project. It works. Register your service in Startup.cs (see CorsServiceCollectionExtensions for details.)

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
    
            services.TryAdd(
                ServiceDescriptor.Transient());
    
            services.TryAdd(
                ServiceDescriptor.Transient());
        }
    
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(minLevel: LogLevel.Verbose);
    
            app.UseCors(corsPolictyBuilder =>
            {
                corsPolictyBuilder.WithOrigins("*.mydomain.com");
            });
    
            app.Run(async context =>
            {
                await context.Response.WriteAsync(
                    $"Is Cors? {context.Request.Headers.ContainsKey(CorsConstants.Origin)}");
            });
        }
    }
    

    Here is the service, awaiting your implementation. You can either copy/paste or inherit from CorsService.

    public class MyCorsService : CorsService, ICorsService
    {
        private ILogger _logger;
    
        public MyCorsService(IOptions options, ILogger logger)
            : base(options)
        {
            _logger = logger;
            _logger.LogInformation("MyCorsService");
        }
    
        public override void ApplyResult(
            CorsResult result, HttpResponse response)
        {
            _logger.LogInformation("ApplyResult");
            base.ApplyResult(result, response);
        }
    
        public override void EvaluateRequest(
            HttpContext context, CorsPolicy policy, CorsResult result)
        {
            _logger.LogInformation("EvaluateRequest");
            base.EvaluateRequest(context, policy, result);
        }
    
        public override void EvaluatePreflightRequest(
            HttpContext context, CorsPolicy policy, CorsResult result)
        {
            _logger.LogInformation("EvaluatePreflightRequest");
            base.EvaluatePreflightRequest(context, policy, result);
        }
    }
    

提交回复
热议问题