asp.net 尽管已添加策略以允许任何和中间件集,但仍被CORS策略阻止

w7t8yxp5  于 2023-02-01  发布在  .NET
关注(0)|答案(1)|浏览(132)

我已经在这个问题上纠结了好几天了。我正在尝试添加CORS策略,这样我的应用程序就不需要CORS插件了(扩展)运行。我已经通过了如何正确实现添加策略和如何订购中间件的多个教程。我的应用程序后端应该发送Map数据到前端,但没有插件,我收到臭名昭著的Access to XMLHttpRequest at 'http://localhost:5001/maps/NaturalEarthII/tilemapresource.xml' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.错误。从我的理解一切都是设置,因为它应该是,但结果不同意,请帮助!没有控制器
配置服务方法:

public void ConfigureServices(IServiceCollection services)
    {
        // Enable Gzip Response Compression for SRTM terrain data
        services.AddResponseCompression(options =>
        {
            options.EnableForHttps = true;
            options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/vnd.quantized-mesh" });
            options.Providers.Add<GzipCompressionProvider>();
        });
        // Add CORS Service so Tile Server works
        services.AddCors(options =>
        {
            //Here ive attepted implementing default and specific policy
            //I've also tried only allowing specific origins and allowing any method + header
            //no luck. I will change this to be more specific once i get maps to show

            options.AddDefaultPolicy(
                builder => builder.AllowAnyOrigin()
                ); 
            options.AddPolicy("allowAny",
                builder => builder.WithOrigins("http://localhost:5001")
                .SetIsOriginAllowed((host) => true)
                .AllowAnyMethod().AllowAnyHeader()
                );
        });
        services.AddControllers();
        //services.AddSpaStaticFiles(config => config.RootPath = "wwwroot");
        services.AddSingleton(typeof(MessageBus), new MessageBus());
    }

配置方法:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, Microsoft.Extensions.Hosting.IHostApplicationLifetime applicationLifetime)
        {
            
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Use Gzip Response Compression for SRTM terrain data
            app.UseResponseCompression();

            // We must set the Content-Type and Content-Encoding for SRTM terrain files,
            // so the Client's Web Browser can display them.
            app.Map("/terrain/srtm", fileApp =>
            {
                fileApp.Run(context =>
                {
                    if (context.Request.Path.Value.EndsWith(".terrain")) {
                        context.Response.Headers["Content-Type"] = "application/vnd.quantized-   mesh";
                        context.Response.Headers["Content-Encoding"] = "gzip";
                    }
                    return context.Response.SendFileAsync(
                        Path.Combine(Directory.GetCurrentDirectory(), ("data/terrain/srtm/" + context.Request.Path.Value)));
                });
            });
            Console.WriteLine(Path.Combine(Directory.GetCurrentDirectory() + "data"));
            // Make the data/maps directory available to clients
            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "data")),
            });
            
            app.UseRouting();
            //Add the default policy thats create in the conf services method
            app.UseCors();

            app.UseAuthorization();

            app.UseWebSockets();

            app.UseEndpoints(endpoints => endpoints.MapControllers().RequireCors("allowAny"));
            bus = (MessageBus)app.ApplicationServices.GetService(typeof(MessageBus));
...

在添加cors我尝试实现默认和特定的政策,我也尝试只允许特定的起源,并允许任何方法+头。没有运气。我会改变这一点,以更具体的,一旦我得到的Map显示

services.AddCors(options =>
            {
                options.AddDefaultPolicy(
                    builder => builder.AllowAnyOrigin()
                    ); 
                options.AddPolicy("allowAny",
                    builder => builder.WithOrigins("http://localhost:5001")
                    .SetIsOriginAllowed((host) => true)
                    .AllowAnyMethod().AllowAnyHeader()
                    );
            });
46scxncf

46scxncf1#

在尝试了无数次让后端工作的尝试后,我放弃了,并在前端实现了反向代理。我现在可以在没有CORS插件的情况下使用我的Web应用程序。
proxy.conf.json:

{
    "/maps":{
        "target": "http://localhost:5001",
        "secure": false
    } 
}

angular.json:

...
"serve": {
          "builder": "@angular-devkit/build-    angular:dev-server",
          "options": {
            "browserTarget": "cesium-angular:build",
            "proxyConfig": "src/proxy.conf.json"
          },
...

相关问题