当前位置:首页 > Web开发 > 正文

Blazor(WebAssembly) + .NETCore 实现斗地主

2024-03-31 Web开发

标签:

原文:Blazor(WebAssembly) + .NETCore 实现斗地主

  之前群里大神发了一个 html5+ .NETCore的斗地主,刚好在看 就尝试重写试试。

  还有就是有些标题党了,因为文章里几乎没有斗地主的相关实现:),这里主要介绍一些Blazor前端的一些方法实现而斗地主的实现总结来说就是获取数据绑定UI,,语法上基本就是Razor,页面上的注入语法等不在重复介绍,完整实现可以查看github:https://github.com/saber-wang/FightLandlord/tree/master/src/BetGame.DDZ.WasmClient,在线演示::5000/

  另外强调一下Blazor WebAssembly 是纯前端框架,所有相关组件等都会下载到浏览器运行,要和MVC、Razor Pages等区分开来

  当前是基于NetCore3.1和Blazor WebAssembly 3.1.0-preview4。

  Blazor WebAssembly默认是没有安装的,在命令行执行下边的命令安装Blazor WebAssembly模板。

1

 

dotnet new -i Microsoft.AspNetCore.Blazor.Templates::3.1.0-preview4.19579.2

 

  

技术图片

  选择Blazor应用,跟着往下就会看到Blazor WebAssembly App模板,如果看不到就在ASP.NET Core3.0和3.1之间切换一下。

  

技术图片

  新建后项目结构如下。

  

技术图片

  一眼看过去,大体和Razor Pages 差不多。Program.cs也和ASP.NET Core差不多,区别是返回了一个IWebAssemblyHostBuilder。

  

public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IWebAssemblyHostBuilder CreateHostBuilder(string[] args) => BlazorWebAssemblyHost.CreateDefaultBuilder() .UseBlazorStartup<Startup>();

  Startup.cs结构也和ASP.NET Core基本一致。Configure中接受的是IComponentsApplicationBuilder,并指定了启动组件

public class Startup { public void ConfigureServices(IServiceCollection services) { //web api 请求 services.AddScoped<ApiService>(); //Js Function调用 services.AddScoped<FunctionHelper>(); //LocalStorage存储 services.AddScoped<LocalStorage>(); //AuthenticationStateProvider实现 services.AddScoped<CustomAuthStateProvider>(); services.AddScoped<AuthenticationStateProvider>(s => s.GetRequiredService<CustomAuthStateProvider>()); //启用认证 services.AddAuthorizationCore(); } public void Configure(IComponentsApplicationBuilder app) { WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include; app.AddComponent<App>("app"); } }

  Blazor WebAssembly 中也支持DI,注入方式与生命周期与ASP.NET Core一致,但是Scope生命周期不太一样,注册的服务的行为类似于 Singleton 服务。

  默认已注入了HttpClient,,,具体可以看介绍。

  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, theres nothing at this address.</p> </LayoutView> </CascadingAuthenticationState> </NotFound> </Router>

  自定义AuthenticationStateProvider并注入为AuthorizeView和CascadingAuthenticationState组件提供认证。

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/web/40350.html