在Blazor web项目中实现身份验证。
在Blazor hybrid项目中添加WebView控件,以在应用程序中呈现Blazor web应用程序。
使用以下代码将WebView与Blazor web应用程序进行关联:
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Maui.Controls;
namespace BlazorHybridApp
{
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
var webView = new BlazorWebView();
webView.RootComponents.Add("app");
Content = webView;
}
}
}
using BlazorHybridApp.Data;
using Microsoft.AspNetCore.Components.WebView.Maui;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui;
using Microsoft.Maui.Controls.Hosting;
using Microsoft.Maui.Essentials;
ApplicationBuilder app = MauiApp.CreateBuilder()
.UseMauiApp()
.ConfigureServices((services) =>
{
services.AddBlazorWebView();
services.AddSingleton();
});
var provider = app.Services.BuildServiceProvider();
var webViewFactory = provider.GetRequiredService();
webViewFactory.ConfigureDefaultClient(client =>
{
// 添加身份验证Cookie
var cookie = Preferences.Get("authCookie", "");
if (!string.IsNullOrEmpty(cookie))
{
client.DefaultRequestHeaders.Add("Cookie", cookie);
}
});
var appHost = new BlazorWebViewAppHost(webViewFactory)
{
RootComponents = (typeof(App).Assembly, "app"),
DefaultProperty = "Content"
};
appHost.AddComponent("app");
var appState = new AppState();
await appState.InitAsync();
app.Services.AddSingleton(appState);
var window = MauiWinUIApplication.Current.Windows.First();
window.Content = appHost.ToNative();
window.Activate();
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using