当前位置:网站首页>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");
});
}
边栏推荐
- Kotlin - i/o flow
- Explanation of vim, makefile and GDB tools
- 【深入理解TcaplusDB技术】TcaplusDB构造数据
- The xdd-plus login prompt on the Qinglong panel is "the current login environment is abnormal. To ensure the security of your account, you cannot log in temporarily. It is recommended to connect the t
- 哪個期貨平臺 交易更安全放心。求推薦。
- Memcached(高性能内存对象缓存)
- Deep understanding of convolution in convolution neural network
- 2. reference
- Is the live interactive function of the applet running in the app?
- [untitled]
猜你喜欢

Repair for a while, decisively reconstruct and take responsibility -- talk about CRM distributed cache optimization

Annual special analysis of China Mobile Banking in 2022

【深入理解TcaplusDB技术】TcaplusDB构造数据

618 Nuggets digital collection? Burberry and other luxury brands fight against metauniverse

Apache shardingsphere 5.1.2 release | new driving API + cloud native deployment to create a high-performance data gateway
![[deeply understand tcapulusdb technology] tmonitor system upgrade](/img/ec/bbfb7e2f19a94b69ec0a6092fd3032.png)
[deeply understand tcapulusdb technology] tmonitor system upgrade

Visualization strategy of Seaborn data overall distribution

Sharing new experiences in home office | community essay solicitation
MySQL constraints (descriptions of various conditions when creating tables)

Sort query results according to the input order of fuzzy query jancode
随机推荐
What is Devops in an article?
Generalized Focal Loss: Learning Qualified and Distributed Bounding Boxes for Dense Object Detection
MySQL - transaction management
2. reference
618 Nuggets digital collection? Burberry and other luxury brands fight against metauniverse
居家辦公初體驗之新得分享| 社區征文
哪個期貨平臺 交易更安全放心。求推薦。
分布式事务处理方案大 PK
启牛商学院app下载证券开户,是安全的吗?有风险嘛?
MySQL约束(创建表时的各种条件说明)
JS 中的集合引用类型
CVPR2022 | 上科大x小红书首次提出动作序列验证任务,可应用于体育赛事打分等多场景
C language elementary order (VI) function
Use map set or list set to store list set
Please, don't use pessimistic locks in high concurrency scenarios!
May the mountains and rivers be safe
Master the basic usage of SQLite3
【深入理解TcaplusDB技术】TcaplusDB业务数据备份
【深入理解TcaplusDB技术】Tmonitor系统升级
[deeply understand tcapulusdb technology] tmonitor system upgrade