Blazor请求被CORS政策阻止

时间:2019-07-22 07:09:48

标签: .net-core cors blazor

我正在尝试从Blazor(客户端)客户端向服务器发送请求,并且不断出现此错误:

  

可从以下位置访问“ [路线]”(从“ [其他路线]”重定向)   原点“ [原点路线]”已被CORS政策阻止:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。如果不透明的响应满足您的需求,请设置请求的   模式设置为“ no-cors”,以在禁用CORS的情况下获取资源。

在服务器上,我已经在管道中添加了CORS扩展名,但无济于事:

服务器启动

public void ConfigureServices(IServiceCollection services) {
            services.AddCors();
            services.AddResponseCompression(options => {
                options.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(new[]
                {
                    MediaTypeNames.Application.Octet,
                    WasmMediaTypeNames.Application.Wasm,
                });
            });
}
 public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

            app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());

            app.UseResponseCompression();

            app.UseMvc();

            app.UseBlazor<Client.Startup>();

        }

Blazor客户请求

public async Task<Catalog> GetCatalogAsync() {
            try {
                HttpRequestMessage message = new HttpRequestMessage {
                    RequestUri = new Uri(BASE_PATH + Routes.GET_CATALOG), //BASE_PATH= 172.XX.XX.XX:8600
                    Method = HttpMethod.Get
                };
                var resp = await this.client.SendAsync(message); // client is HttpClient
                var resultString = await resp.Content.ReadAsStringAsync();
                var result = JsonConvert.DeserializeObject<Catalog>(resultString);
                return data;

            } catch (Exception ex) {

                throw;
            }

        }

控制器

[HttpGet]
[Route(Routes.GET_CATALOG)]
public async Task<Catalog> GetCatalogAsync() {
    try {
        var registry = await this.adminService.GetCatalogAsync();
        return registry;
    } catch (Exception ex) {

        throw;
    }
}

POCO

[Serializeable]
public struct Catalog{
}

我还能做些什么才能到达服务器?是归功于Blazor吗? 如您所见,我已经添加了UseCors(...)

PS
我已经与客户端一起发布了Blazor Server项目。它们位于同一目录中。我将该文件夹放置在计算机上,并且试图从计算机上打开blazor:172.168.18.22:8600/

更新
我也尝试过将标头添加到HttpRequestMessage上无济于事:

HttpRequestMessage message = new HttpRequestMessage {
                    RequestUri = new Uri(BASE_PATH + Routes.GET_CATALOG),
                    Method = HttpMethod.Get,

                };
message.Headers.Add("Access-Control-Allow-Origin","*");
message.Headers.Add("Access-Control-Allow-Credentials", "true");
message.Headers.Add("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Content-Type");

3 个答案:

答案 0 :(得分:0)

@Bercovici Adrian,您为什么要向您的App添加CORS支持?您是否提出跨来源请求?如果您不这样做,请不要尝试通过添加不必要的配置来解决此问题,否则可能会导致更细微的错误。

和往常一样,在没有看到此应用的仓库的情况下,无法为您提供进一步的帮助。

更新:

这是什么 UseBlazor

您应该将您的应用升级到最新版本...

新更新:

对不起,但是我正在使用Blazor的当前预览版本

启动类

 public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddNewtonsoftJson();
        services.AddResponseCompression(opts =>
        {
            opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                new[] { "application/octet-stream" });
        });

    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseBlazorDebugging();
        }
        **// Instead of UseBlazor**
        app.UseClientSideBlazorFiles<Client.Startup>();
        app.UseStaticFiles();

        app.UseRouting();

        **// This configure your end points**
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapDefaultControllerRoute();
            endpoints.MapFallbackToClientSideBlazor<Client.Startup>("index.html");
        });
    }
}

请注意,由于您的客户端和服务器共享同一域,因此我删除了CORS的配置。请使用文档来正确配置CORS。

尝试一下,看看它是否对您有用(我想您的问题与端点的配置有关。以某种方式,在我看来,由于您没有配置端点,因此您的请求被重定向,因此您得到上面显示的消息。)

下一步是检查您的http请求是否正确烹饪。但是首先要检查终点。

答案 1 :(得分:0)

检查从HTTPS运行时是否不发送HTTP请求。例如,如果您在http://172.168.18.22:8600中打开应用程序时向https://172.168.18.22:8600发送请求,则可能会出现问题。

答案 2 :(得分:0)

不知何故,该问题是由于浏览器上缓存的客户端版本太旧导致的,我再也不会忘记在出现此问题后清除浏览器缓存。 谢谢大家的帮助和支持!