BlazorServer入门 简单的登录与注册的设计
🎃 前言:
为了简单起见,本文不采用Autherize标签等直接可用的工具来实现登录和注册的设计。
现创建一个BlazorServer模板,使用的.Net Core版本为3.1。
🎫Blazor需要创建页面(组件)时请直接使用.razor不要使用.cshtml
🍶 Step 1:模拟AuthService(模拟登录逻辑)
public class AuthService
{/// <summary>/// 该工具用来控制前台的js交换/// 这里使用该工具的目的是:调用js的向localStorage(浏览器)中保存信息。[如果你是3.1向上的.NetCore版本,请直接使用ProtectedLocalStorage保存信息]/// </summary>private IJSRuntime jsruntime;public AuthService(IJSRuntime jSRuntime){this.jsruntime = jSRuntime;}public static List<TestUser> list = new List<TestUser>() { new TestUser() { username = "root",password = "1234", nickname = "礼堂丁真", age = 27 } };public TestUser LoginMethod(string username,string password){if (list.Any(it => it.username.Equals(username) && it.password.Equals(password))){TestUser loginer = list.Where(it => it.username.Equals(username)).FirstOrDefault();jsruntime.InvokeVoidAsync("localStorage.setItem", new object[2] { "currentUser", JsonConvert.SerializeObject(loginer) });return loginer;} elsereturn null;}public (bool,string) Register(string username,string password,string nickname){if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(nickname))return (false, "Not NULL!");if (list.Any(it => it.username.Equals(username))){return (false,"用户名不能重复");}AuthService.list.Add(new TestUser() { username = username, password = password, nickname = nickname, age = 20 });jsruntime.InvokeVoidAsync("alert", new object[1] { "success" });return (true, "已注册");}
}public class TestUser
{public string username { get; set; }public string password { get; set; }public string nickname { get; set; }public int? age { get; set; }
}
注册到StartUp中
public void ConfigureServices(IServiceCollection services)
{services.AddRazorPages();services.AddServerSideBlazor();services.AddSingleton<WeatherForecastService>();services.AddScoped<AuthService>(); //注册IOC
}
🐟 Step 2:添加登录和注册页面(.razor组件)
@page "/login"@using Data;@inject AuthService auth
@inject NavigationManager nvm
@inject IJSRuntime runtime<h3>Login</h3><span>UN:</span>
<input type="text" class="input-group-text" id="UN" @bind-value="UserName" /><br /><span>PW:</span>
<input type="text" class="input-group-text" id="PW" @bind-value="PassWord" /><br /><button @onclick="()=> { DoLogin(UserName,PassWord); }">Submit</button>@code {public string UserName { get; set; }public string PassWord { get; set; }public bool hid = true;public void DoLogin(string UserName,string PassWord){var User = auth.LoginMethod(UserName, PassWord);if (User != null)nvm.NavigateTo($@"/");else{runtime.InvokeVoidAsync("alert", "Login failed");}}}
@page "/register"@using Data@inject AuthService auth
@inject NavigationManager nvm
@inject IJSRuntime jsruntime<h3>Register</h3><span>UN:</span>
<input type="text" class="input-group-text" @bind-value="UserName" />
<br /><span>PW:</span>
<input type="password" class="input-group-text" @bind-value="PassWord" />
<br />
<span>PW_confirm:</span>
<input type="password" class="input-group-text" @bind-value="PassWord2" />
<br /><button class="btn-info" @onclick="()=> { RegisterMethod(UserName, PassWord, PassWord2); }"> regist </button>@code {public string UserName { get; set; }public string PassWord { get; set; }public string PassWord2 { get; set; }public void RegisterMethod(string UserName,string PassWord,string PassWord2){var res = auth.Register(UserName, PassWord, PassWord2);if (res.Item1){jsruntime.InvokeVoidAsync("alert", "register success");nvm.NavigateTo("/login");}else{jsruntime.InvokeVoidAsync("alert", "register failed");}}}
为什么拦截其他页面,需要在你的其他页面添加OnAfterRenderAsync方法从写。
并在发放中检查存放的Storage信息是否有效。若找不到则直接导航到登录页。
例如:
@inherits LayoutComponentBase
@inject IJSRuntime runtime
@inject NavigationManager nvm<div class="sidebar"><NavMenu />
</div><div class="main"><div class="top-row px-4"><a href="https://docs.microsoft.com/aspnet/" target="_blank">About</a></div><div class="content px-4">@Body</div>
</div>@code{protected override async Task OnAfterRenderAsync(bool firstRender){//检查是否带有登录信息string user = await runtime.InvokeAsync<string>("localStorage.getItem", "currentUser");if (string.IsNullOrEmpty(user)){nvm.NavigateTo("/login");}base.OnAfterRender(firstRender);}}
🌮 Step 3:测试截图
项目代码已上传至gitcode
罗马苏丹默罕默德 / BlazorServerTest · GitCode