Blazer Web程序集应用程序无法使用阻止的CORS策略调用grpc-web调用

问题描述

我正在用grpc-web服务调用测试我的Blazer webassmbly应用程序。但是呼叫失败,并显示以下消息。有关如何解决此问题的任何想法?这些都是我的笔记本电脑的本地设备,尚未部署到任何地方。

 blazor.webassembly.js:1 Debugging hotkey: Shift+Alt+D (when application has focus)
blazor.webassembly.js:1 blazor Loaded 6.51 MB resourcesThis application was built with linking (tree shaking) disabled. Published applications will be significantly smaller.
dotnet.3.2.0.js:1 >>>mono_wasm_get_loaded_files
GRPCTest:1 Access to fetch at 'https://localhost:5001/greet.Greeter/SayHello' from origin 'https://localhost:44326' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs,set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
:5001/greet.Greeter/SayHello:1 Failed to load resource: net::ERR_Failed
blazor.webassembly.js:1 crit: Microsoft.AspNetCore.Components.WebAssembly.Rendering.WebAssemblyRenderer[100]
      Unhandled exception rendering component: Status(StatusCode="Internal",Detail="Error starting gRPC call. JSException: TypeError: Failed to fetch",DebugException="WebAssembly.JSException: TypeError: Failed to fetch
        at System.Net.Http.WebAssemblyHttpHandler.doFetch (System.Threading.Tasks.taskcompletionsource`1[TResult] tcs,System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) <0x301c200 + 0x00a30> in <filename unkNown>:0 
        at System.Net.Http.WebAssemblyHttpHandler.SendAsync (System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) <0x2fed868 + 0x00174> in <filename unkNown>:0 
        at Grpc.Net.Client.Web.GrpcWebHandler.SendAsyncCore (System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) [0x00092] in /_/src/Grpc.Net.Client.Web/GrpcWebHandler.cs:137 
        at Grpc.Net.Client.Internal.GrpcCall`2[TRequest,TResponse].runcall (System.Net.Http.HttpRequestMessage request,System.Nullable`1[T] timeout) [0x0020c] in /_/src/Grpc.Net.Client/Internal/GrpcCall.cs:477 ")
Grpc.Core.RpcException: Status(StatusCode="Internal",DebugException="WebAssembly.JSException: TypeError: Failed to fetch
  at System.Net.Http.WebAssemblyHttpHandler.doFetch (System.Threading.Tasks.taskcompletionsource`1[TResult] tcs,System.Threading.CancellationToken cancellationToken) <0x301c200 + 0x00a30> in <filename unkNown>:0 
  at System.Net.Http.WebAssemblyHttpHandler.SendAsync (System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) <0x2fed868 + 0x00174> in <filename unkNown>:0 
  at Grpc.Net.Client.Web.GrpcWebHandler.SendAsyncCore (System.Net.Http.HttpRequestMessage request,System.Threading.CancellationToken cancellationToken) [0x00092] in /_/src/Grpc.Net.Client.Web/GrpcWebHandler.cs:137 
  at Grpc.Net.Client.Internal.GrpcCall`2[TRequest,System.Nullable`1[T] timeout) [0x0020c] in /_/src/Grpc.Net.Client/Internal/GrpcCall.cs:477 ")
  at GRPCBlazorApp.Pages.GRPCTest.OnInitializedAsync () [0x0005a] in C:\Users\sbaku\source\repos\GRPCBlazorApp\GRPCBlazorApp\Pages\GRPCTest.razor:16 
  at Microsoft.AspNetCore.Components.ComponentBase.RunInitAndSetParametersAsync () <0x2c61318 + 0x0013a> in <filename unkNown>:0 
  at Microsoft.AspNetCore.Components.RenderTree.Renderer.GetErrorHandledTask (System.Threading.Tasks.Task taskToHandle) <0x2eda540 + 0x000b6> in <filename unkNown>:0 
f.printErr @ blazor.webassembly.js:1
f.preRun.push.window.Blazor._internal.dotNetCriticalError @ blazor.webassembly.js:1
_mono_wasm_invoke_js_unmarshalled @ dotnet.3.2.0.js:1
do_icall @ 00755c3a:0x10f924
do_icall_wrapper @ 00755c3a:0x50b6a
interp_exec_method @ 00755c3a:0x2588e
interp_runtime_invoke @ 00755c3a:0xf7391
mono_jit_runtime_invoke @ 00755c3a:0xddb3d
do_runtime_invoke @ 00755c3a:0x3ba85
mono_runtime_try_invoke @ 00755c3a:0xcfdb
try_invoke_perform_wait_callback @ 00755c3a:0xb62e0
worker_callback @ 00755c3a:0x9a7a3
fire_tp_callback @ 00755c3a:0x105481
mono_background_exec @ 00755c3a:0xeb5ee
Module._mono_background_exec @ dotnet.3.2.0.js:1
pump_message @ dotnet.3.2.0.js:1
setTimeout (async)
_schedule_background_exec @ dotnet.3.2.0.js:1
mono_threads_schedule_background_job @ 00755c3a:0x14dbd
ves_icall_System_Threading_ThreadPool_RequestWorkerThread @ 00755c3a:0xa0025
ves_icall_System_Threading_ThreadPool_RequestWorkerThread_raw @ 00755c3a:0x9fecf
do_icall @ 00755c3a:0x10f790
do_icall_wrapper @ 00755c3a:0x50b6a
interp_exec_method @ 00755c3a:0x2588e
interp_runtime_invoke @ 00755c3a:0xf7391
mono_jit_runtime_invoke @ 00755c3a:0xddb3d
do_runtime_invoke @ 00755c3a:0x3ba85
mono_runtime_try_invoke @ 00755c3a:0xcfdb
mono_runtime_invoke @ 00755c3a:0x44b39
mono_wasm_invoke_method @ 00755c3a:0xca6a7
Module._mono_wasm_invoke_method @ dotnet.3.2.0.js:1
call_method @ dotnet.3.2.0.js:1
set_task_failure @ dotnet.3.2.0.js:1
(anonymous) @ dotnet.3.2.0.js:1
Promise.then (async)
js_to_mono_obj @ dotnet.3.2.0.js:1
_mono_wasm_invoke_js_with_args @ dotnet.3.2.0.js:1
do_icall @ 00755c3a:0x10f8b1
do_icall_wrapper @ 00755c3a:0x50b6a
interp_exec_method @ 00755c3a:0x2588e
interp_runtime_invoke @ 00755c3a:0xf7391
mono_jit_runtime_invoke @ 00755c3a:0xddb3d
do_runtime_invoke @ 00755c3a:0x3ba85
mono_runtime_invoke_checked @ 00755c3a:0x96a2
mono_runtime_try_invoke_array @ 00755c3a:0x66c26
ves_icall_InternalInvoke @ 00755c3a:0xb44ff
ves_icall_InternalInvoke_raw @ 00755c3a:0xb3ffd
do_icall @ 00755c3a:0x10f8b1
do_icall_wrapper @ 00755c3a:0x50b6a
interp_exec_method @ 00755c3a:0x2588e
interp_runtime_invoke @ 00755c3a:0xf7391
mono_jit_runtime_invoke @ 00755c3a:0xddb3d
do_runtime_invoke @ 00755c3a:0x3ba85
mono_runtime_try_invoke @ 00755c3a:0xcfdb
mono_runtime_invoke @ 00755c3a:0x44b39
mono_wasm_invoke_method @ 00755c3a:0xca6a7
Module._mono_wasm_invoke_method @ dotnet.3.2.0.js:1
call_method @ dotnet.3.2.0.js:1
(anonymous) @ dotnet.3.2.0.js:1
beginInvokeDotNetFromJS @ blazor.webassembly.js:1
s @ blazor.webassembly.js:1
e.invokeMethodAsync @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
r @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
r @ blazor.webassembly.js:1
d @ blazor.webassembly.js:1
f @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
(anonymous) @ blazor.webassembly.js:1
e.onGlobalEvent @ blazor.webassembly.js:1
Show 43 more frames from Library code

enter image description here

GRPC-WEB服务代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
//using GrpcWebService.Services;

namespace GrpcWebService
{
    public class Startup
    {
        // 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.AddGrpc();
            services.AddAuthorization();
            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllHeaders",builder =>
                      {
                          builder.AllowAnyOrigin()
                                 .AllowAnyHeader()
                                 .AllowAnyMethod();
                      });
            });
        }

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

            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapGrpcService<GreeterService>()
                    .RequireCors(cors => cors.AllowAnyHeader().AllowAnyMethod());
                //endpoints.MapGrpcService<WeatherForecastsService>().EnableGrpcWeb()
                //    .RequireCors(cors => cors.AllowAnyHeader().AllowAnyMethod()
                //        .WithOrigins("http://localhost:54070","https://localhost:44316"));

                endpoints.MapGet("/",async context =>
                {
                    await context.Response.WriteAsync("Communication with gRPC endpoints must be made through a gRPC client. To learn how to create a client,visit: https://go.microsoft.com/fwlink/?linkid=2086909");
                });
            });
        }
    }
}

开拓者代码

using System;
using System.Net.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Text;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Grpc.Net.Client.Web;
using Grpc.Net.Client;

namespace GRPCBlazorApp
{
    public class Program
    {
        public static async Task Main(string[] args)
        {
            var builder = WebAssemblyHostBuilder.CreateDefault(args);
            builder.RootComponents.Add<App>("app");

            builder.Services.AddScoped(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });

            builder.Services.AddSingleton(services =>
            {
                // Get the service address from appsettings.json
                //var config = services.GetrequiredService<IConfiguration>();
                //var backendUrl = config["BackendUrl"];
                var backendUrl = "https://localhost:5001";

                // Create a channel with a GrpcWebHandler that is addressed to the backend server.
                //
                // GrpcWebText is used because server streaming requires it. If server streaming is not used in your app
                // then GrpcWeb is recommended because it produces smaller messages.
                var httpHandler = new GrpcWebHandler(GrpcWebMode.GrpcWebText,new httpclienthandler());

                return GrpcChannel.ForAddress(backendUrl,new GrpcChannelOptions { HttpHandler = httpHandler });
            });

            await builder.Build().RunAsync();
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...