这就是我创建项目的方式
到目前为止我已经:
我的问题是 HttpClient 或 HttpClientFactory 注册,到目前为止我所做的:
我的下一步是使用 HTTP 通信的通用解决方案,例如就我而言,我已经编写了自己的,但是让我们以 refit 为例,如何注册 refit 并在 FE 中使用它?
问题是,在客户端,由于交互性,你不能像以前一样注册它,因为它必须在 BE 上
builder.Services.AddHttpClient("WebAPI", client =>
client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)
现在怎么办?我的场景非常复杂,这就是我想要实现的目标:
最后,我确实阅读了很多有关渲染模式和其他所有内容的内容,我发现以当前的心态很难实现我的目标,任何建议和具体答案将非常感激。
我有一组与您非常相似的要求,虽然这不完全是答案,而不仅仅是评论,但这就是我所学到的。
将所有 WASM 页面移至 WASM 客户端
Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly"
,并将所有可共享组件移至 Razor 组件库 Project Sdk="Microsoft.NET.Sdk.Razor"
。然后通过 Web 服务器的程序将它们导入到 Web 服务器Project Sdk="Microsoft.NET.Sdk.Web"
...
builder.Services
.AddRazorComponents()
.AddInteractiveServerComponents()
.AddInteractiveWebAssemblyComponents();
...
...
app.AddInteractiveServerRenderMode()
.AddInteractiveWebAssemblyRenderMode()
.AddAdditionalAssemblies(
typeof(Client._Imports).Assembly //the client ProjectReference's the shared if needed.
);
航线也需要进口...
<Router AppAssembly="@typeof(WebProgram).Assembly" AdditionalAssemblies="new[] {
typeof(Client._Imports).Assembly,
}">
...
在客户的程序中,您需要...
builder.Services.AddHttpClient<HttpClient>("aNamedClient",
getClientConfiguration(Configuration.GetSection("TheConfig")))
.AddHttpMessageHandler<ApplicationIdentityCookieHandler>();
注意,
getClientConfiguration
仅从 appsettings.json 配置 http 客户端的路径和主机 - ApplicationIdentityCookieHandler
是其中的重要部分。它是客户端应用程序将 Identity cookie 获取到 HttpClient 请求中的方式。我的看起来像...
private class ApplicationIdentityCookieHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
request.SetBrowserRequestCredentials(BrowserRequestCredentials.Include); // get that cookie
request.SetBrowserRequestMode(BrowserRequestMode.Cors); // allow it to go to the api.
return await base.SendAsync(request, cancellationToken);
}
}
您还需要在 Web 服务器中执行相同的操作,但不要将
ApplicationIdentityCookieHandler
添加到 http 客户端。这是因为 Blazor Web App 的渲染方式 - @rendermode RenderMode.InteractiveWebAssembly
不会立即在 WASM 中启动,服务器首先处理渲染它,然后再将控制权传递给 WASM 运行时。这有一个额外的警告,如果服务器尝试调用受身份保护的 Web API 端点,它将失败并显示 40[1/3] - 我正在尝试为此找到更好的解决方案。这在评论中已注明——您必须在两侧添加 http 客户端服务。
跨 FE 和 BE 的身份要求您:
builder.Services.AddAuthorization(...);
builder.Services.AddAuthentication(...);
builder.Services.ConfigureApplicationCookie(...);
var dataProtect = builder.Services.AddDataProtection();
dataProtect
.PersistKeysToFileSystem(new DirectoryInfo(keyPersistencePath))
.SetApplicationName(applicationName);
builder.Services.AddCors(setupAction=> ...);