当前位置:网站首页>Blazor webassembly integrates Ocelot gateway to solve cross domain problems

Blazor webassembly integrates Ocelot gateway to solve cross domain problems

2022-06-21 13:40:00 Guo Mahua

Blazor WebAssembly Integrate Ocelot The gateway incidentally solves cross domain problems

We know that cross domain requests are usually blocked by browsers . This is a security mechanism provided by the browser , That is, scripts under one domain name are not allowed to request data from another domain name .

Please note that Blazor WebAssembly Of ASP.NET Core hosted Pattern , That is, the template has Client,Server,Share Three projects .

Problem description

stay blazor I have encountered such problems in application development , My project requires sixorseven different site interfaces , There is a unified login site , Order interface site , Store interface site , Third party channel sites, etc . And I hope to pass HttpClientFactory To get HttpClient For the request .

as everyone knows , IHttpClientFactory There are many ways of using :

  • Basic usage
  • Name the client
  • Typed client
  • Generated clients

Suppose you use the named client method , We can easily distinguish between different names BaseAddress Of HttpClient, But the company already has a primary HttpClient Encapsulated class library , therefore , I have to use the method of typing clients .

Here is an example ( contain IOC In the container HttpMessageHandler The addition of ):

 public static class ServiceClientExtension
    {
        public static WebAssemblyHostBuilder AddServiceClient(this WebAssemblyHostBuilder builder)
        {
            builder.Services.AddScoped<PlatformRequestHandler>();
            builder.Services
                .AddHttpClient<IServiceClient, ServiceClients.ServiceClient>((sp, client) =>
                {
                    var option = sp.GetService<ModuleOption>();
                    if (string.IsNullOrWhiteSpace(option.BaseAddress))
                    {
                        option.BaseAddress = builder.HostEnvironment.BaseAddress;
                    }
                    client.BaseAddress = new Uri(option.BaseAddress);
                })
                .AddHttpMessageHandler();

            return builder;
        }

        private static IHttpClientBuilder AddHttpMessageHandler(this IHttpClientBuilder builder)
        {
            builder.ConfigureHttpMessageHandlerBuilder(cfg =>
            {
                var handlers = cfg.Services.GetServices<DelegatingHandler>();
                foreach (var delegatingHandler in handlers)
                {
                    cfg.AdditionalHandlers.Add(delegatingHandler);
                }
            });
            return builder;
        }
    }

therefore , I need a request forwarding site , Unified help me forward requests to different sites . Naturally, I think of Ocelot.Ocelot It is an excellent open source gateway project .

my Blazor In the project Server, It has the following functions :

  • Integrate Ocelot, Forward requests as a gateway
  • Integrate Azure ApplicationInsights, Record interface request exceptions
  • Tune up Blazor.Client Program

Cut a long story short

I won't go into details here Ocelot Application , Just introduce it in Blazor The use of .

Integrate Ocelot Example :

public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureAppConfiguration((hostingContext, builder) =>
                {
                    builder
                        .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                        .AddJsonFile($"/Ocelot/Ocelot.json", true, true)
                        .AddJsonFile($"/Ocelot/ocelot.{hostingContext.HostingEnvironment.EnvironmentName.ToLower()}.json", true, true)
                        .AddEnvironmentVariables();
                })
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }

When called by the client , take HttpClientFactory Of BaseAddress Designated as builder.HostEnvironment.BaseAddress( See example above ), By requesting url Add forwarding node ID in , Such as /login, then Ocelot According to your profile , find /login The corresponding site , Forward request :

var request = new HttpRequestMessage(HttpMethod.Get, "/login/Auth/UserInfo");

How to make Ocelot Do not block the middleware pipeline , When the forwarding route path is not found , Go to the next middleware

It should be noted that ,Ocelot It is usually required to block the middleware pipeline , therefore , It can lead to blazor Page navigation failed , Even a normal page Jump will be forwarded as a request . therefore , We need to be right about Ocelot Middleware transformation , When it cannot find a forwarding route , Automatically enter the next middleware .

Examples are as follows :

        public static IApplicationBuilder UseOcelotWhenRouteMatch(this IApplicationBuilder app)
        {
            app.MapWhen(context =>
            {
                var internalConfigurationResponse = context.RequestServices.GetRequiredService<IInternalConfigurationRepository>().Get();
                if (internalConfigurationResponse.IsError || internalConfigurationResponse.Data.Routes.Count == 0)
                {
                    return false;
                }

                var internalConfiguration = internalConfigurationResponse.Data;
                var downstreamRouteFinder = context.RequestServices.GetRequiredService<IDownstreamRouteProviderFactory>().Get(internalConfiguration);

                var response = downstreamRouteFinder.Get(context.Request.Path, context.Request.QueryString.ToString(),
                    context.Request.Method, internalConfiguration, context.Request.Host.ToString());
                return !response.IsError && !string.IsNullOrEmpty(response.Data?.Route?.DownstreamRoute?.FirstOrDefault()?.DownstreamScheme);
            }, appBuilder => appBuilder.UseOcelot().Wait());

            return app;
        }

Startup.cs

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseWebAssemblyDebugging();
            }

            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseOcelotWhenRouteMatch();

            app.UseEndpoints(builder =>
            {
                builder.MapFallbackToFile("index.html");
            });
        }
原网站

版权声明
本文为[Guo Mahua]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202221433592506.html