Blazor Wasm 最近更新到了3.2.0-preview1,支持了WebSocket同時啟動類也有所修改,我就把這個文章重新修改一下。
Blazor Wasm先在已經更新到3.2.0正式版,本文代碼也已更新
之前群里大神發了一個 html5+ .NETCore的斗地主,剛好在看Blazor WebAssembly 就嘗試重寫試試。
這里主要介紹Blazor的依賴注入,認證與授權,WebSocket的使用,JS互操作等,完整實現可以查看github:https://github.com/saber-wang/FightLandlord/tree/master/src/BetGame.DDZ.WasmClient,在線演示:http://39.106.159.180:31000/
另外強調一下Blazor WebAssembly 是純前端框架,所有相關組件等都會下載到瀏覽器運行,要和MVC、Razor Pages等區分開來
當前是基於NetCore3.1和Blazor WebAssembly 3.2.0 ,安裝Vs 2019 16.6更新后就會附帶Blazor WebAssembly模板。
選擇Blazor應用,跟着往下就會看到Blazor WebAssembly App模板,如果看不到就在ASP.NET Core3.0和3.1之間切換一下。
新建后項目結構如下。
一眼看過去,大體和Razor Pages 差不多。Program.cs中創建了一個WebAssemblyHostBuilder,然后指定啟動容器,代碼非常簡單。
public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); await builder.Build().RunAsync(); }
Blazor WebAssembly 中也支持DI,注入方式與生命周期與ASP.NET Core一致,但是Scope生命周期不太一樣,注冊的服務的行為類似於 Singleton
服務。
在WebAssemblyHostBuilder中有一個Services屬性用來注冊服務
public static async Task Main(string[] args)
{
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.Services.AddScoped<ApiService>();
builder.Services.AddScoped<FunctionHelper>();
builder.Services.AddScoped<LocalStorage>();
builder.Services.AddScoped<CustomAuthStateProvider>();
builder.Services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthStateProvider>());
builder.Services.AddAuthorizationCore(c=> {
c.AddPolicy("default", a => a.RequireAuthenticatedUser());
c.DefaultPolicy = c.GetPolicy("default");
});
builder.Services.AddScoped(sp=>new ClientWebSocket());
builder.RootComponents.Add<App>("app");
builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) });
WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
await builder.Build().RunAsync();
}
默認已注入了IJSRuntime,NavigationManager,具體可以看官方文檔介紹。
App.razor中定義了路由和默認路由,修改添加AuthorizeRouteView和CascadingAuthenticationState以支持AuthorizeView、AuthenticationState等用於認證和獲取當前的身份驗證狀態。
<Router AppAssembly="@typeof(Program).Assembly"> <Found Context="routeData"> <AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" /> </Found> <NotFound> <CascadingAuthenticationState> <LayoutView Layout="@typeof(MainLayout)"> <p>Sorry, there's nothing at this address.</p> </LayoutView> </CascadingAuthenticationState> </NotFound> </Router>
自定義AuthenticationStateProvider並注入為AuthorizeView和CascadingAuthenticationState組件提供認證。
builder.Services.AddScoped<CustomAuthStateProvider>(); builder.Services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthStateProvider>()); //在wasm中沒有默認配置,所以需要設置一下 builder.Services.AddAuthorizationCore(c=> { c.AddPolicy("default", a => a.RequireAuthenticatedUser()); c.DefaultPolicy = c.GetPolicy("default"); });
CustomAuthStateProvider的實現如下。
public class CustomAuthStateProvider : AuthenticationStateProvider { ApiService _apiService; Player _playerCache; public CustomAuthStateProvider(ApiService apiService) { _apiService = apiService; } public override async Task<AuthenticationState> GetAuthenticationStateAsync() { var player = _playerCache??= await _apiService.GetPlayer(); if (player == null) { return new AuthenticationState(new ClaimsPrincipal()); } else { //認證通過則提供ClaimsPrincipal var user = Utils.GetClaimsIdentity(player); return new AuthenticationState(user); } } /// <summary> /// 通知AuthorizeView等用戶狀態更改 /// </summary> public void NotifyAuthenticationState() { NotifyAuthenticationStateChanged(GetAuthenticationStateAsync()); } /// <summary> /// 提供Player並通知AuthorizeView等用戶狀態更改 /// </summary> public void NotifyAuthenticationState(Player player) { _playerCache = player; NotifyAuthenticationState(); } }
我們這個時候就可以在組件上添加AuthorizeView根據用戶是否有權查看來選擇性地顯示 UI,該組件公開了一個 AuthenticationState 類型的 context 變量,可以使用該變量來訪問有關已登錄用戶的信息。
<AuthorizeView> <Authorized> //認證通過 @context.User </Authorized> <NotAuthorized> //認證不通過 </NotAuthorized> </AuthorizeView>
使身份驗證狀態作為級聯參數
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
獲取當前用戶信息
private async Task GetPlayer() { var user = await authenticationStateTask; if (user?.User?.Identity?.IsAuthenticated == true) { player = new Player { Balance = Convert.ToInt32(user.User.FindFirst(nameof(Player.Balance)).Value), GameState = user.User.FindFirst(nameof(Player.GameState)).Value, Id = user.User.FindFirst(nameof(Player.Id)).Value, IsOnline = Convert.ToBoolean(user.User.FindFirst(nameof(Player.IsOnline)).Value), Nick = user.User.FindFirst(nameof(Player.Nick)).Value, Score = Convert.ToInt32(user.User.FindFirst(nameof(Player.Score)).Value), }; await ConnectWebsocket(); } }
注冊用戶並通知AuthorizeView狀態更新
private async Task GetOrAddPlayer(MouseEventArgs e) { GetOrAddPlayering = true; player = await ApiService.GetOrAddPlayer(editNick); this.GetOrAddPlayering = false; if (player != null) { CustomAuthStateProvider.NotifyAuthenticationState(player); await ConnectWebsocket(); } }
JavaScript 互操作,雖然很希望完全不操作JavaScript,但目前版本的Web WebAssembly不太現實,例如彈窗、本地存儲等,Blazor中操作JavaScript主要靠IJSRuntime 抽象,在重構的時候遇到最多的錯誤就是類型轉換和索引溢出錯誤:)。
從Blazor操作JavaScript比較簡單,操作的JavaScript需要是公開的,這里實現從Blazor調用alert和localStorage如下
public class FunctionHelper { private readonly IJSRuntime _jsRuntime; public FunctionHelper(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public ValueTask Alert(object message) { //無返回值使用InvokeVoidAsync return _jsRuntime.InvokeVoidAsync("alert", message); } }
public class LocalStorage { private readonly IJSRuntime _jsRuntime; private readonly static JsonSerializerOptions SerializerOptions = new JsonSerializerOptions(); public LocalStorage(IJSRuntime jsRuntime) { _jsRuntime = jsRuntime; } public ValueTask SetAsync(string key, object value) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Cannot be null or empty", nameof(key)); } var json = JsonSerializer.Serialize(value, options: SerializerOptions); return _jsRuntime.InvokeVoidAsync("localStorage.setItem", key, json); } public async ValueTask<T> GetAsync<T>(string key) { if (string.IsNullOrEmpty(key)) { throw new ArgumentException("Cannot be null or empty", nameof(key)); } //有返回值使用InvokeAsync var json =await _jsRuntime.InvokeAsync<string>("localStorage.getItem", key); if (json == null) { return default; } return JsonSerializer.Deserialize<T>(json, options: SerializerOptions); } public ValueTask DeleteAsync(string key) { return _jsRuntime.InvokeVoidAsync( $"localStorage.removeItem",key); } }
從JavaScript調用C#方法則需要把C#方法使用[JSInvokable]特性標記且必須為公開的。調用C#靜態方法看這里,這里主要介紹調用C#的實例方法。
因為Blazor Wasm暫時不支持ClientWebSocket,所以我們用JavaScript互操作來實現WebSocket的鏈接與C#方法的回調。
使用C#實現一個調用JavaScript的WebSocket,並使用DotNetObjectReference.Create包裝一個實例傳遞給JavaScript方法的參數(dotnetHelper),這里直接傳遞了當前實例。
[JSInvokable] public async Task ConnectWebsocket() { Console.WriteLine("ConnectWebsocket"); var serviceurl = await ApiService.ConnectWebsocket(); //TODO ConnectWebsocket
if (!string.IsNullOrWhiteSpace(serviceurl)) await _jsRuntime.InvokeAsync<string>("newWebSocket", serviceurl, DotNetObjectReference.Create(this)); }
JavaScript代碼里使用參數(dotnetHelper)接收的實例調用C#方法(dotnetHelper.invokeMethodAsync('方法名',方法參數...))。
var gsocket = null; var gsocketTimeId = null; function newWebSocket(url, dotnetHelper) { console.log('newWebSocket'); if (gsocket) gsocket.close(); gsocket = null; gsocket = new WebSocket(url); gsocket.onopen = function (e) { console.log('websocket connect'); //調用C#的onopen();
dotnetHelper.invokeMethodAsync('onopen') }; gsocket.onclose = function (e) { console.log('websocket disconnect'); dotnetHelper.invokeMethodAsync('onclose') gsocket = null; clearTimeout(gsocketTimeId); gsocketTimeId = setTimeout(function () { console.log('websocket onclose ConnectWebsocket'); //調用C#的ConnectWebsocket();
dotnetHelper.invokeMethodAsync('ConnectWebsocket'); //_self.ConnectWebsocket.call(_self);
}, 5000); }; gsocket.onmessage = function (e) { try { console.log('websocket onmessage'); var msg = JSON.parse(e.data); //調用C#的onmessage();
dotnetHelper.invokeMethodAsync('onmessage', msg); //_self.onmessage.call(_self, msg);
} catch (e) { console.log(e); return; } }; gsocket.onerror = function (e) { console.log('websocket error'); gsocket = null; clearTimeout(gsocketTimeId); gsocketTimeId = setTimeout(function () { console.log('websocket onerror ConnectWebsocket'); dotnetHelper.invokeMethodAsync('ConnectWebsocket'); //_self.ConnectWebsocket.call(_self);
}, 5000); }; }
Blazor中已經實現了Websocket,現在我們可以很簡單的操作Websocket。
public async Task ConnectWebsocket() { Console.WriteLine("ConnectWebsocket"); //獲取Websocket鏈接 var serviceurl = await ApiService.ConnectWebsocket(); if (!string.IsNullOrWhiteSpace(serviceurl)) { wsConnectState = 1010; //鏈接Websocket await clientWebSocket.ConnectAsync(new Uri(serviceurl),default); //后台接收消息 ReceiveMessages(); //鏈接Websocket時調用 await onopen(); //await _jsRuntime.InvokeAsync<string>("newWebSocket", serviceurl, DotNetObjectReference.Create(this)); } }
ReceiveMessages的實現如下
private async Task ReceiveMessages() { List<byte> vs = new List<byte>(); while (true) { Memory<byte> memory = new Memory<byte>(new byte[1024]); var res = await clientWebSocket.ReceiveAsync(memory, default); var bt = memory.ToArray().Take(res.Count); vs.AddRange(bt); if (res.EndOfMessage) { if (res.MessageType == WebSocketMessageType.Close) { onclose(); } else { var jsonDocument = JsonSerializer.Deserialize<object>(vs.ToArray()); vs.Clear(); await onmessage(jsonDocument); } //當前方法在后台執行,所以我們需要手動更新UI StateHasChanged(); } } }
onopen,onclose,onmessage實現如下
public async Task onopen() { Console.WriteLine("websocket connect"); wsConnectState = 1; await GetDesks(); StateHasChanged(); } public void onclose() { Console.WriteLine("websocket disconnect"); wsConnectState = 0; } public async Task onmessage(object msgobjer) { try { var jsonDocument = JsonSerializer.Deserialize<object>(msgobjer.ToString()); if (jsonDocument is JsonElement msg) { if (msg.TryGetProperty("type", out var element) && element.ValueKind == JsonValueKind.String) { Console.WriteLine(element.ToString()); if (element.GetString() == "Sitdown") { Console.WriteLine(msg.GetProperty("msg").GetString()); var deskId = msg.GetProperty("deskId").GetInt32(); foreach (var desk in desks) { if (desk.Id.Equals(deskId)) { var pos = msg.GetProperty("pos").GetInt32(); Console.WriteLine(pos); var player = JsonSerializer.Deserialize<Player>(msg.GetProperty("player").ToString()); switch (pos) { case 1: desk.player1 = player; break; case 2: desk.player2 = player; break; case 3: desk.player3 = player; break; } break; } } } else if (element.GetString() == "Standup") { Console.WriteLine(msg.GetProperty("msg").GetString()); var deskId = msg.GetProperty("deskId").GetInt32(); foreach (var desk in desks) { if (desk.Id.Equals(deskId)) { var pos = msg.GetProperty("pos").GetInt32(); Console.WriteLine(pos); switch (pos) { case 1: desk.player1 = null; break; case 2: desk.player2 = null; break; case 3: desk.player3 = null; break; } break; } } } else if (element.GetString() == "GameStarted") { Console.WriteLine(msg.GetProperty("msg").GetString()); currentChannel.msgs.Insert(0, msg); } else if (element.GetString() == "GameOvered") { Console.WriteLine(msg.GetProperty("msg").GetString()); currentChannel.msgs.Insert(0, msg); } else if (element.GetString() == "GamePlay") { ddzid = msg.GetProperty("ddzid").GetString(); ddzdata = JsonSerializer.Deserialize<GameInfo>(msg.GetProperty("data").ToString()); Console.WriteLine(msg.GetProperty("data").ToString()); stage = ddzdata.stage; selectedPokers = new int?[55]; if (playTips.Any()) playTips.RemoveRange(0, playTips.Count); playTipsIndex = 0; if (this.stage == "游戲結束") { foreach (var ddz in this.ddzdata.players) { if (ddz.id == player.Nick) { this.player.Score += ddz.score; break; } } } if (this.ddzdata.operationTimeoutSeconds > 0 && this.ddzdata.operationTimeoutSeconds < 100) await this.operationTimeoutTimer(); } else if (element.GetString() == "chanmsg") { currentChannel.msgs.Insert(0, msg); if (currentChannel.msgs.Count > 120) currentChannel.msgs.RemoveRange(100, 20); } } Console.WriteLine("onmessage_end"); } } catch (Exception ex) { Console.WriteLine($"onmessage_ex_{ex.Message}_{msgobjer}"); } }
在html5版中有使用setTimeout來刷新用戶的等待操作時間,我們可以通過一個折中方法實現
private CancellationTokenSource timernnnxx { get; set; } //js setTimeout private async Task setTimeout(Func<Task> action, int time) { try { timernnnxx = new CancellationTokenSource(); await Task.Delay(time, timernnnxx.Token); await action?.Invoke(); } catch (Exception ex) { Console.WriteLine($"setTimeout_{ex.Message}"); } } private async Task operationTimeoutTimer() { Console.WriteLine("operationTimeoutTimer_" + this.ddzdata.operationTimeoutSeconds); if (timernnnxx != null) { timernnnxx.Cancel(false); Console.WriteLine("operationTimeoutTimer 取消"); } this.ddzdata.operationTimeoutSeconds--; StateHasChanged(); if (this.ddzdata.operationTimeoutSeconds > 0) { await setTimeout(this.operationTimeoutTimer, 1000); } }
其他組件相關如數據綁定,事件處理,組件參數等等推薦直接看文檔。
瀏覽器下載的部分資源如下
Blazor Wasm