Blazor请求被CORS策略拦截。

15

我正在尝试从Blazor(客户端)客户端向服务器发送请求,但是一直收到以下错误:

由于CORS策略,来自源站点“[origin route]”的请求访问“[route]”(重定向自“[other route]”)被阻止。未在所请求资源的“Access-Control-Allow-Origin”标头中找到“[origin route]”。如果您需要一个不透明的响应,则将请求模式设置为'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(...)
P.S 我已经发布了我的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");

1
你的客户端 Blazor 是否与服务器共享同一域名? - enet
你在Blazor中发起请求的地址是什么?你的Blazor应用程序所在的地址是什么? - codevision
1
它们确实共享相同的域。 - Bercovici Adrian
1
如果是这样,问题不在于跨域资源共享(CORS)。这是用户代码的问题。 - enet
5个回答

2
一些问题似乎是由于浏览器缓存了一个非常旧的客户端版本所致。此后,我再也不会忘记清除浏览器缓存了。 感谢大家的帮助和支持!

1

你需要在中间件中指定你的策略名称。

builder.Services.AddCors(policy =>{

    policy.AddPolicy("Policy_Name", builder =>         
      builder.WithOrigins("https://*:5001/")
        .SetIsOriginAllowedToAllowWildcardSubdomains()
        .AllowAnyOrigin()
  
    
 );});

// Configure the HTTP request pipeline.

 app.UseCors("Policy_Name");

1
对我来说,我在app.MapControllers()之后使用了app.UseCors()。修正顺序后,它起作用了。

0

我已确认我正在运行http。 - Bercovici Adrian
抱歉,我还是要问一下,您确定您没有向HTTP和完全相同的端口发出请求吗? - codevision
我正在向完全相同的端口发出请求,请求是http而不是https。因此,我的服务器托管在:172.22.XX.YY:8600,我向该地址发出请求。 - Bercovici Adrian
你能打开Chrome网页控制台,尝试使用fetch发起相同的请求吗?客户端Blazor在幕后只是调用fetch,因此这将是公平的故障排除。 - codevision
我遇到了相同的错误,但它毫无意义。客户端/服务器架构的整个重点显然在于客户端和服务器可以处于不同的位置。 - Paul McCarthy

0

@Bercovici Adrian,为什么您要为您的应用程序添加CORS支持?您是否进行跨域请求?如果没有,请不要通过添加不必要的配置来解决问题,这可能会导致更微妙的错误。

通常情况下,如果没有看到该应用程序的repo,我们无法提供进一步帮助。

更新:

这个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请求是否已正确处理。但首先,请检查端点。

我正在使用 .NET Core 2.1 进行服务器项目。 - Bercovici Adrian
为什么不升级?展示你所做的http请求代码...展示你的Web Api...展示启动代码...帮助我们帮助你。 - enet
请查看我的答案中的“新更新”部分。 - enet
我认为我没有理解关于域的问题。客户端将被调用的位置不会在部署应用程序的计算机上。 - Bercovici Adrian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接