diff --git a/src/admin/Bootstrap.Admin/Controllers/AccountController.cs b/src/admin/Bootstrap.Admin/Controllers/AccountController.cs index dfd8ad13..3d605133 100644 --- a/src/admin/Bootstrap.Admin/Controllers/AccountController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/AccountController.cs @@ -38,7 +38,7 @@ namespace Bootstrap.Admin.Controllers [HttpGet] public async Task Lock() { - if (!User.Identity.IsAuthenticated) return Login(); + if (!User.Identity!.IsAuthenticated) return Login(); var authenticationType = User.Identity.AuthenticationType; await HttpContext.SignOutAsync(); @@ -61,7 +61,7 @@ namespace Bootstrap.Admin.Controllers /// [HttpPost] [IgnoreAntiforgeryToken] - public Task Lock([FromServices]ISMSProvider provider, string userName, string password, string authType) + public Task Lock([FromServices] ISMSProvider provider, string userName, string password, string authType) { // 根据不同的登陆方式 Task ret; @@ -77,14 +77,14 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public ActionResult Login([FromQuery]string? appId = null, [FromQuery]string view = "") + public ActionResult Login([FromQuery] string? appId = null, [FromQuery] string view = "") { if (DictHelper.RetrieveSystemModel()) { ViewBag.UserName = "Admin"; ViewBag.Password = "123789"; } - return User.Identity.IsAuthenticated ? (ActionResult)Redirect("~/Home/Index") : LoginView(view, new LoginModel(appId)); + return User.Identity!.IsAuthenticated ? (ActionResult)Redirect("~/Home/Index") : LoginView(view, new LoginModel(appId)); } private ViewResult LoginView(string view, LoginModel model) @@ -105,7 +105,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpPost()] - public async Task Mobile([FromServices]ISMSProvider provider, string phone, string code) + public async Task Mobile([FromServices] ISMSProvider provider, string phone, string code) { if (string.IsNullOrEmpty(phone) || string.IsNullOrEmpty(code)) return RedirectLogin(); @@ -130,10 +130,8 @@ namespace Bootstrap.Admin.Controllers if (UserHelper.Save(user) && !string.IsNullOrEmpty(user.Id)) { // 根据配置文件设置默认角色 - var roles = RoleHelper.Retrieves().Where(r => provider.Options.Roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id); -#nullable disable + var roles = RoleHelper.Retrieves().Where(r => provider.Options.Roles.Any(rl => rl.Equals(r.RoleName, StringComparison.OrdinalIgnoreCase))).Select(r => r.Id!); RoleHelper.SaveByUserId(user.Id, roles); -#nullable restore } } } @@ -142,7 +140,7 @@ namespace Bootstrap.Admin.Controllers private IActionResult RedirectLogin() { - var query = Request.Query.Aggregate(new Dictionary(), (d, v) => + var query = Request.Query.Aggregate(new Dictionary(), (d, v) => { d.Add(v.Key, v.Value.ToString()); return d; @@ -184,7 +182,7 @@ namespace Bootstrap.Admin.Controllers /// /// The logout. [HttpGet] - public async Task Logout([FromQuery]string appId) + public async Task Logout([FromQuery] string appId) { await HttpContext.SignOutAsync(); return Redirect(QueryHelpers.AddQueryString(Request.PathBase + CookieAuthenticationDefaults.LoginPath, "AppId", appId ?? BootstrapAppContext.AppId)); @@ -203,7 +201,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public IActionResult Gitee([FromServices]IConfiguration config) + public IActionResult Gitee([FromServices] IConfiguration config) { var enabled = config.GetValue($"{nameof(GiteeOptions)}:Enabled", false); return Challenge(enabled ? GiteeDefaults.AuthenticationScheme : CookieAuthenticationDefaults.AuthenticationScheme); @@ -214,7 +212,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public IActionResult GitHub([FromServices]IConfiguration config) + public IActionResult GitHub([FromServices] IConfiguration config) { var enabled = config.GetValue($"{nameof(GitHubOptions)}:Enabled", false); return Challenge(enabled ? GitHubDefaults.AuthenticationScheme : CookieAuthenticationDefaults.AuthenticationScheme); @@ -225,7 +223,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public IActionResult Tencent([FromServices]IConfiguration config) + public IActionResult Tencent([FromServices] IConfiguration config) { var enabled = config.GetValue($"{nameof(TencentOptions)}:Enabled", false); return Challenge(enabled ? TencentDefaults.AuthenticationScheme : CookieAuthenticationDefaults.AuthenticationScheme); @@ -236,7 +234,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public IActionResult Alipay([FromServices]IConfiguration config) + public IActionResult Alipay([FromServices] IConfiguration config) { var enabled = config.GetValue($"{nameof(AlipayOptions)}:Enabled", false); return Challenge(enabled ? AlipayDefaults.AuthenticationScheme : CookieAuthenticationDefaults.AuthenticationScheme); @@ -247,7 +245,7 @@ namespace Bootstrap.Admin.Controllers /// /// [HttpGet] - public IActionResult WeChat([FromServices]IConfiguration config) + public IActionResult WeChat([FromServices] IConfiguration config) { var enabled = config.GetValue($"{nameof(WeChatOptions)}:Enabled", false); return Challenge(enabled ? WeChatDefaults.AuthenticationScheme : CookieAuthenticationDefaults.AuthenticationScheme); diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/CategoryController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/CategoryController.cs index 1158b60f..98c69430 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/CategoryController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/CategoryController.cs @@ -32,7 +32,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet] public IEnumerable RetrieveMenus() { - return MenuHelper.RetrieveAllMenus(User.Identity.Name).OrderBy(m => m.Name).Select(m => m.Name); + return MenuHelper.RetrieveAllMenus(User.Identity!.Name).OrderBy(m => m.Name).Select(m => m.Name); } /// @@ -42,7 +42,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet] public IEnumerable RetrieveParentMenus() { - return MenuHelper.RetrieveMenus(User.Identity.Name).Where(m => m.Menus.Count() > 0).OrderBy(m => m.Name).Select(m => m.Name); + return MenuHelper.RetrieveMenus(User.Identity!.Name).Where(m => m.Menus.Count() > 0).OrderBy(m => m.Name).Select(m => m.Name); } /// @@ -52,7 +52,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet("{id}")] public bool ValidateMenuBySubMenu(string id) { - return !MenuHelper.RetrieveAllMenus(User.Identity.Name).Where(m => m.ParentId == id).Any(); + return !MenuHelper.RetrieveAllMenus(User.Identity!.Name).Where(m => m.ParentId == id).Any(); } /// @@ -62,7 +62,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet("{id}")] public bool ValidateParentMenuById(string id) { - return MenuHelper.RetrieveAllMenus(User.Identity.Name).FirstOrDefault(m => m.Id == id)?.IsResource == 0; + return MenuHelper.RetrieveAllMenus(User.Identity!.Name).FirstOrDefault(m => m.Id == id)?.IsResource == 0; } } } diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/LogsController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/LogsController.cs index 6d42a050..2be32e71 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/LogsController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/LogsController.cs @@ -38,11 +38,11 @@ namespace Bootstrap.Admin.Controllers.Api { value.UserAgent = Request.Headers["User-Agent"]; var agent = new UserAgent(value.UserAgent); - value.Ip = HttpContext.Connection.RemoteIpAddress.ToIPv4String(); + value.Ip = HttpContext.Connection.RemoteIpAddress?.ToIPv4String() ?? ""; value.Browser = $"{agent.Browser?.Name} {agent.Browser?.Version}"; value.OS = $"{agent.OS?.Name} {agent.OS?.Version}"; value.City = ipLocator.Locate(value.Ip); - value.UserName = User.Identity.Name ?? string.Empty; + value.UserName = User.Identity?.Name ?? string.Empty; return LogHelper.Save(value); } } diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/MenusController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/MenusController.cs index 4ff6474a..13a71a42 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/MenusController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/MenusController.cs @@ -25,7 +25,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet] public QueryData Get([FromQuery]QueryMenuOption value) { - return value.RetrieveData(User.Identity.Name); + return value.RetrieveData(User.Identity!.Name); } /// @@ -66,7 +66,7 @@ namespace Bootstrap.Admin.Controllers.Api ret = MenuHelper.RetrieveMenusByRoleId(id); break; case "user": - ret = MenuHelper.RetrieveMenus(User.Identity.Name); + ret = MenuHelper.RetrieveMenus(User.Identity!.Name); break; } return ret; diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/MessagesController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/MessagesController.cs index 5fbc3a4f..930aeb7f 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/MessagesController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/MessagesController.cs @@ -28,16 +28,16 @@ namespace Bootstrap.Admin.Controllers.Api switch (id) { case "inbox": - ret = MessageHelper.Inbox(User.Identity.Name).ToList(); + ret = MessageHelper.Inbox(User.Identity!.Name).ToList(); break; case "sendmail": - ret = MessageHelper.SendMail(User.Identity.Name).ToList(); + ret = MessageHelper.SendMail(User.Identity!.Name).ToList(); break; case "mark": - ret = MessageHelper.Mark(User.Identity.Name).ToList(); + ret = MessageHelper.Mark(User.Identity!.Name).ToList(); break; case "trash": - ret = MessageHelper.Trash(User.Identity.Name).ToList(); + ret = MessageHelper.Trash(User.Identity!.Name).ToList(); break; } return ret; @@ -52,12 +52,12 @@ namespace Bootstrap.Admin.Controllers.Api { var mcm = new MessageCountModel { - InboxCount = MessageHelper.Inbox(User.Identity.Name).Count(), - SendmailCount = MessageHelper.SendMail(User.Identity.Name).Count(), - MarkCount = MessageHelper.Mark(User.Identity.Name).Count(), - TrashCount = MessageHelper.Trash(User.Identity.Name).Count() + InboxCount = MessageHelper.Inbox(User.Identity!.Name).Count(), + SendmailCount = MessageHelper.SendMail(User.Identity!.Name).Count(), + MarkCount = MessageHelper.Mark(User.Identity!.Name).Count(), + TrashCount = MessageHelper.Trash(User.Identity!.Name).Count() }; return mcm; } } -} \ No newline at end of file +} diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/NewController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/NewController.cs index 02496093..14ec2597 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/NewController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/NewController.cs @@ -38,7 +38,7 @@ namespace Bootstrap.Admin.Controllers public bool Put([FromBody]User value) { var ret = false; - var userName = User.Identity.Name; + var userName = User.Identity!.Name; if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(value.Id)) { if (value.UserStatus == UserStates.ApproveUser) diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/NotificationsController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/NotificationsController.cs index cdad1689..83205b44 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/NotificationsController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/NotificationsController.cs @@ -43,11 +43,11 @@ namespace Bootstrap.Admin.Controllers.Api var tasksCount = task.Count(); //Message - var message = MessageHelper.Retrieves(User.Identity.Name); + var message = MessageHelper.Retrieves(User.Identity!.Name); var messagesCount = message.Count(); message = message.Take(6); - message.AsParallel().ForAll(m => m.FromIcon = Url.Content(m.FromIcon)); + message.AsParallel().ForAll(m => m.FromIcon = Url.Content(m.FromIcon) ?? string.Empty); //Apps var apps = ExceptionsHelper.Retrieves().Where(n => n.Category != "DB"); diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/OnlineUsersController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/OnlineUsersController.cs index 152a5987..ea41c177 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/OnlineUsersController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/OnlineUsersController.cs @@ -23,7 +23,7 @@ namespace Bootstrap.Admin.Controllers.Api /// /// [HttpGet()] - public IEnumerable Get([FromServices]IOnlineUsers onlineUSers) + public IEnumerable Get([FromServices] IOnlineUsers onlineUSers) { return onlineUSers.OnlineUsers.OrderByDescending(u => u.LastAccessTime); } @@ -35,7 +35,7 @@ namespace Bootstrap.Admin.Controllers.Api /// /// [HttpGet("{id}")] - public IEnumerable> Get(string id, [FromServices]IOnlineUsers onlineUSers) + public IEnumerable> Get(string id, [FromServices] IOnlineUsers onlineUSers) { var user = onlineUSers.OnlineUsers.FirstOrDefault(u => u.ConnectionId == id); return user?.RequestUrls ?? new KeyValuePair[0]; @@ -49,7 +49,7 @@ namespace Bootstrap.Admin.Controllers.Api [AllowAnonymous] public bool Put() { - var ip = Request.HttpContext.Connection.RemoteIpAddress.ToIPv4String(); + var ip = Request.HttpContext.Connection.RemoteIpAddress?.ToIPv4String() ?? ""; if (_loginUsers.TryGetValue(ip, out var user)) { user.Reset(); diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/ProfilesController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/ProfilesController.cs index 55a42f8f..54b5f0e1 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/ProfilesController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/ProfilesController.cs @@ -27,10 +27,10 @@ namespace Bootstrap.Admin.Controllers.Api /// [HttpPost("{id}")] [ButtonAuthorize(Url = "~/Admin/Profiles", Auth = "saveIcon")] - public JsonResult Post(string id, [FromServices]IWebHostEnvironment env, [FromForm]DeleteFileCollection files) + public JsonResult Post(string id, [FromServices] IWebHostEnvironment env, [FromForm] DeleteFileCollection files) { if (!id.Equals("Delete", StringComparison.OrdinalIgnoreCase)) return new JsonResult(new object()); - var userName = User.Identity.Name; + var userName = User.Identity!.Name; var fileName = files.Key; fileName = Path.Combine(env.WebRootPath, $"images{Path.DirectorySeparatorChar}uploader{Path.DirectorySeparatorChar}{fileName}"); @@ -40,7 +40,7 @@ namespace Bootstrap.Admin.Controllers.Api var filePath = Path.Combine(env.WebRootPath, webSiteUrl.Replace("~", string.Empty).Replace('/', Path.DirectorySeparatorChar).TrimStart(Path.DirectorySeparatorChar) + fileName); var fileSize = new FileInfo(filePath).Length; var iconName = $"{fileName}?v={DateTime.Now.Ticks}"; - var previewUrl = Url.Content($"{webSiteUrl}{iconName}"); + var previewUrl = Url.Content($"{webSiteUrl}{iconName}") ?? string.Empty; if (!string.IsNullOrEmpty(userName)) UserHelper.SaveUserIconByName(userName, iconName); return new JsonResult(new @@ -72,11 +72,11 @@ namespace Bootstrap.Admin.Controllers.Api /// [HttpPost] [ButtonAuthorize(Url = "~/Admin/Profiles", Auth = "saveIcon")] - public async Task Post([FromServices]IWebHostEnvironment env, IFormCollection files) + public async Task Post([FromServices] IWebHostEnvironment env, IFormCollection files) { - var previewUrl = string.Empty; + string? previewUrl = null; long fileSize = 0; - var userName = User.Identity.Name; + var userName = User.Identity!.Name; var fileName = string.Empty; if (files.Files.Count > 0) { @@ -95,7 +95,7 @@ namespace Bootstrap.Admin.Controllers.Api } return new JsonResult(new { - initialPreview = new string[] { previewUrl }, + initialPreview = new string[] { previewUrl ?? string.Empty }, initialPreviewConfig = new object[] { new { caption = "新头像", size = fileSize, showZoom = true, key = fileName } }, @@ -109,10 +109,10 @@ namespace Bootstrap.Admin.Controllers.Api /// [HttpPut] [ButtonAuthorize(Url = "~/Admin/Profiles", Auth = "saveDisplayName,savePassword,saveApp,saveTheme")] - public bool Put([FromBody]User value) + public bool Put([FromBody] User value) { var ret = false; - if (value.UserName.Equals(User.Identity.Name, StringComparison.OrdinalIgnoreCase)) + if (value.UserName.Equals(User.Identity!.Name, StringComparison.OrdinalIgnoreCase)) { ret = value.UserStatus switch { diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/TasksController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/TasksController.cs index 47b92541..74ad7e70 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/TasksController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/TasksController.cs @@ -24,7 +24,7 @@ namespace Bootstrap.Admin.Controllers.Api [HttpGet] public IEnumerable Get() { - return TaskServicesManager.ToList().Select(s => new { s.Name, Status = s.Status.ToString(), s.LastRuntime, s.CreatedTime, s.NextRuntime, LastRunResult = s.Triggers.First().LastResult.ToString(), TriggerExpression = s.Triggers.FirstOrDefault().ToString() }).OrderBy(s => s.Name); + return TaskServicesManager.ToList().Select(s => new { s.Name, Status = s.Status.ToString(), s.LastRuntime, s.CreatedTime, s.NextRuntime, LastRunResult = s.Triggers.First().LastResult.ToString(), TriggerExpression = s.Triggers.First().ToString() }).OrderBy(s => s.Name); } /// diff --git a/src/admin/Bootstrap.Admin/Controllers/Api/UsersController.cs b/src/admin/Bootstrap.Admin/Controllers/Api/UsersController.cs index 8474530d..f33955c5 100644 --- a/src/admin/Bootstrap.Admin/Controllers/Api/UsersController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/Api/UsersController.cs @@ -61,7 +61,7 @@ namespace Bootstrap.Admin.Controllers.Api bool ret; if (string.IsNullOrEmpty(value.Id)) { - value.Description = string.Format("管理员{0}创建用户", User.Identity.Name); + value.Description = string.Format("管理员{0}创建用户", User.Identity!.Name); value.ApprovedBy = User.Identity.Name; value.ApprovedTime = DateTime.Now; ret = UserHelper.Save(value); diff --git a/src/admin/Bootstrap.Admin/Controllers/HomeController.cs b/src/admin/Bootstrap.Admin/Controllers/HomeController.cs index f79dc285..4355fee0 100644 --- a/src/admin/Bootstrap.Admin/Controllers/HomeController.cs +++ b/src/admin/Bootstrap.Admin/Controllers/HomeController.cs @@ -19,7 +19,7 @@ namespace Bootstrap.Admin.Controllers /// public IActionResult Index([FromServices]IConfiguration configuration) { - var model = new HeaderBarModel(User.Identity.Name); + var model = new HeaderBarModel(User.Identity!.Name); var homeUrl = DictHelper.RetrieveHomeUrl(User.Identity.Name, model.AppId); var useBlazor = DictHelper.RetrieveEnableBlazor(); return homeUrl.Equals("~/Home/Index", System.StringComparison.OrdinalIgnoreCase) ? (useBlazor ? Redirect("~/Pages") : (IActionResult)View(model)) : Redirect(homeUrl); diff --git a/src/admin/Bootstrap.Admin/HealthChecks/DBHealthCheck.cs b/src/admin/Bootstrap.Admin/HealthChecks/DBHealthCheck.cs index 461d6d64..66c3c743 100644 --- a/src/admin/Bootstrap.Admin/HealthChecks/DBHealthCheck.cs +++ b/src/admin/Bootstrap.Admin/HealthChecks/DBHealthCheck.cs @@ -58,7 +58,7 @@ namespace Bootstrap.Admin.HealthChecks }; // 检查 当前用户 账户权限 - var loginUser = _httpContextAccessor.HttpContext?.User.Identity.Name; + var loginUser = _httpContextAccessor.HttpContext?.User.Identity?.Name; var userName = loginUser ?? "Admin"; var dictsCount = 0; var menusCount = 0; @@ -88,11 +88,11 @@ namespace Bootstrap.Admin.HealthChecks { error = ex; } - var data = new Dictionary() + var data = new Dictionary() { - { "ConnectionString", db.ConnectionString }, - { "Reference", DbContextManager.Create()?.GetType().Assembly.FullName ?? db.Widget }, - { "DbType", db?.ProviderName }, + { "ConnectionString", db.ConnectionString ?? string.Empty }, + { "Reference", DbContextManager.Create()?.GetType().Assembly.FullName ?? db.Widget ?? string.Empty }, + { "DbType", db?.ProviderName ?? string.Empty }, { "Dicts", dictsCount }, { "LoginName", userName }, { "DisplayName", displayName }, diff --git a/src/admin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs b/src/admin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs index 21396fc0..717bbbe2 100644 --- a/src/admin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs +++ b/src/admin/Bootstrap.Admin/HealthChecks/GiteeHttpHealthCheck.cs @@ -24,7 +24,7 @@ namespace Bootstrap.Admin.HealthChecks public GiteeHttpHealthCheck(GiteeHttpClient client, IHttpContextAccessor accessor) { _client = client; - _client.HttpClient.BaseAddress = new Uri($"{accessor.HttpContext.Request.Scheme}://{accessor.HttpContext.Request.Host}{accessor.HttpContext.Request.PathBase}"); + _client.HttpClient.BaseAddress = new Uri($"{accessor.HttpContext!.Request.Scheme}://{accessor.HttpContext?.Request.Host}{accessor.HttpContext?.Request.PathBase}"); } /// diff --git a/src/admin/Bootstrap.Admin/Models/NavigatorBarModel.cs b/src/admin/Bootstrap.Admin/Models/NavigatorBarModel.cs index 06218eb3..31c51674 100644 --- a/src/admin/Bootstrap.Admin/Models/NavigatorBarModel.cs +++ b/src/admin/Bootstrap.Admin/Models/NavigatorBarModel.cs @@ -16,7 +16,7 @@ namespace Bootstrap.Admin.Models /// 构造函数 /// /// - public NavigatorBarModel(ControllerBase controller) : this(controller.User.Identity.Name, $"~{controller.Request.Path}") + public NavigatorBarModel(ControllerBase controller) : this(controller.User.Identity!.Name, $"~{controller.Request.Path}") { } diff --git a/src/admin/Bootstrap.Admin/Models/ProfilesModel.cs b/src/admin/Bootstrap.Admin/Models/ProfilesModel.cs index 3ba04e25..59e87eda 100644 --- a/src/admin/Bootstrap.Admin/Models/ProfilesModel.cs +++ b/src/admin/Bootstrap.Admin/Models/ProfilesModel.cs @@ -45,14 +45,14 @@ namespace Bootstrap.Admin.Models // 数据库存储的个人图片有后缀 default.jpg?v=1234567 fileName = fileName.Split('?').FirstOrDefault(); - if (File.Exists(fileName)) + if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName)) { Size = new FileInfo(fileName).Length; FileName = Path.GetFileName(fileName); } } - if (controller.User.Identity.AuthenticationType != CookieAuthenticationDefaults.AuthenticationScheme) External = true; + if (controller.User.Identity!.AuthenticationType != CookieAuthenticationDefaults.AuthenticationScheme) External = true; // 设置 当前用户默认应用名称 AppName = Applications.FirstOrDefault(app => app.Key == AppId).Value; diff --git a/src/admin/Bootstrap.Admin/Pages/Components/BootstrapAdminEditContextDataAnnotationsExtensions.cs b/src/admin/Bootstrap.Admin/Pages/Components/BootstrapAdminEditContextDataAnnotationsExtensions.cs index 726f37fb..234bcd94 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/BootstrapAdminEditContextDataAnnotationsExtensions.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/BootstrapAdminEditContextDataAnnotationsExtensions.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; @@ -53,13 +54,13 @@ namespace Bootstrap.Admin.Pages.Components { if (!validationResult.MemberNames.Any()) { - messages.Add(new FieldIdentifier(editContext.Model, fieldName: string.Empty), validationResult.ErrorMessage); + messages.Add(new FieldIdentifier(editContext.Model, fieldName: string.Empty), validationResult.ErrorMessage!); continue; } foreach (var memberName in validationResult.MemberNames) { - messages.Add(editContext.Field(memberName), validationResult.ErrorMessage); + messages.Add(editContext.Field(memberName), validationResult.ErrorMessage!); } } editContext.NotifyValidationStateChanged(); @@ -81,14 +82,13 @@ namespace Bootstrap.Admin.Pages.Components editForm.ValidateProperty(propertyValue, validationContext, results); messages.Clear(fieldIdentifier); - messages.Add(fieldIdentifier, results.Select(result => result.ErrorMessage)); + messages.Add(fieldIdentifier, results.Select(result => result.ErrorMessage!)); editContext.NotifyValidationStateChanged(); } } -#nullable disable - internal static bool TryGetValidatableProperty(in FieldIdentifier fieldIdentifier, out PropertyInfo propertyInfo) + internal static bool TryGetValidatableProperty(in FieldIdentifier fieldIdentifier, [MaybeNullWhen(false)] out PropertyInfo propertyInfo) { var cacheKey = (ModelType: fieldIdentifier.Model.GetType(), fieldIdentifier.FieldName); if (!_propertyInfoCache.TryGetValue(cacheKey, out propertyInfo)) @@ -96,11 +96,10 @@ namespace Bootstrap.Admin.Pages.Components // Validator.TryValidateProperty 只能对 Public 属性生效 propertyInfo = cacheKey.ModelType.GetProperty(cacheKey.FieldName); - _propertyInfoCache[cacheKey] = propertyInfo; + if (propertyInfo != null) _propertyInfoCache[cacheKey] = propertyInfo; } return propertyInfo != null; } -#nullable restore } } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/DefaultLayoutComponentBase.cs b/src/admin/Bootstrap.Admin/Pages/Components/DefaultLayoutComponentBase.cs index cc4c9af4..d82b47e6 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/DefaultLayoutComponentBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/DefaultLayoutComponentBase.cs @@ -105,7 +105,7 @@ namespace Bootstrap.Admin.Pages.Components } var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); - if (!state.User.Identity.IsAuthenticated) + if (!state.User.Identity!.IsAuthenticated) { NavigationManager?.NavigateTo("/Account/Login?returnUrl=" + WebUtility.UrlEncode(new Uri(NavigationManager.Uri).PathAndQuery)); } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/EqualToValidator.cs b/src/admin/Bootstrap.Admin/Pages/Components/EqualToValidator.cs index 808d7433..a02824e2 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/EqualToValidator.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/EqualToValidator.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Components; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Linq; namespace Bootstrap.Admin.Pages.Components { @@ -39,7 +40,7 @@ namespace Bootstrap.Admin.Pages.Components { var val = propertyValue?.ToString() ?? ""; if (val != Value) - results.Add(new ValidationResult(ErrorMessage, new string[] { context.MemberName })); + results.Add(new ValidationResult(ErrorMessage, string.IsNullOrEmpty(context.MemberName) ? Enumerable.Empty() : new string[] { context.MemberName })); } } } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/LgbEditFormBase.cs b/src/admin/Bootstrap.Admin/Pages/Components/LgbEditFormBase.cs index 36eb1d14..915d9be6 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/LgbEditFormBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/LgbEditFormBase.cs @@ -106,7 +106,7 @@ namespace Bootstrap.Admin.Pages.Components /// public void ValidateProperty(object? propertyValue, ValidationContext context, List results) { - if (_validatorCache.TryGetValue((this, context.ObjectType, context.MemberName), out var validator)) + if (_validatorCache.TryGetValue((this, context.ObjectType, context.MemberName ?? string.Empty), out var validator)) { validator.ValidateProperty(propertyValue, context, results); validator.ToggleMessage(results, true); diff --git a/src/admin/Bootstrap.Admin/Pages/Components/LgbTableHeader.cs b/src/admin/Bootstrap.Admin/Pages/Components/LgbTableHeader.cs index 6d3b3459..e8592417 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/LgbTableHeader.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/LgbTableHeader.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Components.Forms; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; namespace Bootstrap.Admin.Pages.Components @@ -32,7 +33,9 @@ namespace Bootstrap.Admin.Pages.Components /// /// 获得/设置 ValueExpression 表达式 /// - [Parameter] public Expression>? ValueExpression { get; set; } + [Parameter] + [NotNull] + public Expression>? ValueExpression { get; set; } /// /// 获得/设置 是否排序 默认 false diff --git a/src/admin/Bootstrap.Admin/Pages/Components/RequiredValidator.cs b/src/admin/Bootstrap.Admin/Pages/Components/RequiredValidator.cs index e66f2c01..74d38903 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/RequiredValidator.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/RequiredValidator.cs @@ -1,6 +1,7 @@ -using System.Collections.Generic; +using Microsoft.AspNetCore.Components; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using Microsoft.AspNetCore.Components; +using System.Linq; namespace Bootstrap.Admin.Pages.Components { @@ -34,7 +35,7 @@ namespace Bootstrap.Admin.Pages.Components var val = propertyValue?.ToString() ?? ""; if (!AllowEmptyString && val == string.Empty) { - results.Add(new ValidationResult(ErrorMessage, new string[] { context.MemberName })); + results.Add(new ValidationResult(ErrorMessage, string.IsNullOrEmpty(context.MemberName) ? Enumerable.Empty() : new string[] { context.MemberName })); } } } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/StringLengthValidator.cs b/src/admin/Bootstrap.Admin/Pages/Components/StringLengthValidator.cs index c7f7790e..43719a4e 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/StringLengthValidator.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/StringLengthValidator.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Linq; using Microsoft.AspNetCore.Components; namespace Bootstrap.Admin.Pages.Components @@ -33,7 +34,7 @@ namespace Bootstrap.Admin.Pages.Components public override void Validate(object? propertyValue, ValidationContext context, List results) { var val = propertyValue?.ToString() ?? ""; - if (val.Length > Length) results.Add(new ValidationResult(ErrorMessage, new string[] { context.MemberName })); + if (val.Length > Length) results.Add(new ValidationResult(ErrorMessage, string.IsNullOrEmpty(context.MemberName) ? Enumerable.Empty() : new string[] { context.MemberName })); } } } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/TabSetBase.cs b/src/admin/Bootstrap.Admin/Pages/Components/TabSetBase.cs index a4303ada..cebdf0eb 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/TabSetBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/TabSetBase.cs @@ -120,11 +120,14 @@ namespace Bootstrap.Admin.Pages.Components tabId = await JSRuntime.RemoveTabAsync(tab.Id); Tabs.Remove(tab); tab = Tabs.FirstOrDefault(t => t.Id == tabId); - tab.SetActive(true); + if (tab != null) + { + tab.SetActive(true); - page = Pages.FirstOrDefault(p => p.Id == tabId); - if (page != null) page.Active = true; - StateHasChanged(); + page = Pages.FirstOrDefault(p => p.Id == tabId); + if (page != null) page.Active = true; + StateHasChanged(); + } } } } diff --git a/src/admin/Bootstrap.Admin/Pages/Components/TableBase.cs b/src/admin/Bootstrap.Admin/Pages/Components/TableBase.cs index 0070f332..23f0cc1e 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/TableBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/TableBase.cs @@ -5,6 +5,7 @@ using Microsoft.AspNetCore.Components.Forms; using Microsoft.JSInterop; using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Bootstrap.Admin.Pages.Components @@ -18,6 +19,7 @@ namespace Bootstrap.Admin.Pages.Components /// 获得 IJSRuntime 实例 /// [Inject] + [NotNull] protected IJSRuntime? JSRuntime { get; set; } /// @@ -278,12 +280,12 @@ namespace Bootstrap.Admin.Pages.Components } /// - /// OnAfterRenderAsync 方法 + /// OnAfterRender 方法 /// - protected override async System.Threading.Tasks.Task OnAfterRenderAsync(bool firstRender) + protected override void OnAfterRender(bool firstRender) { // 调用客户端脚本 - await JSRuntime.InitTableAsync(RetrieveId(), firstRender); + JSRuntime.InitTableAsync(RetrieveId(), firstRender); } /// diff --git a/src/admin/Bootstrap.Admin/Pages/Components/ValidateInputBase.cs b/src/admin/Bootstrap.Admin/Pages/Components/ValidateInputBase.cs index 748d4a8f..17371724 100644 --- a/src/admin/Bootstrap.Admin/Pages/Components/ValidateInputBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Components/ValidateInputBase.cs @@ -4,6 +4,7 @@ using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; @@ -67,11 +68,6 @@ namespace Bootstrap.Admin.Pages.Components /// protected string ValidCss { get; set; } = ""; - /// - /// 获得/设置 显示名称 默认为 - - /// - protected string DisplayName { get; set; } = "-"; - /// /// OnInitialized 方法 /// @@ -123,7 +119,7 @@ namespace Bootstrap.Admin.Pages.Components var messages = results.Where(item => item.MemberNames.Any(m => m == FieldIdentifier.FieldName)); if (messages.Any()) { - ErrorMessage = messages.First().ErrorMessage; + ErrorMessage = messages.First().ErrorMessage ?? string.Empty; ValidCss = "is-invalid"; // 控件自身数据验证时显示 tooltip @@ -147,9 +143,9 @@ namespace Bootstrap.Admin.Pages.Components /// /// /// - protected override bool TryParseValueFromString(string value, out TItem result, out string? validationErrorMessage) + protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TItem result, [NotNullWhen(false)] out string? validationErrorMessage) { - if (typeof(TItem) == typeof(string)) + if (!string.IsNullOrEmpty(value) && typeof(TItem) == typeof(string)) { result = (TItem)(object)value; validationErrorMessage = null; @@ -160,22 +156,20 @@ namespace Bootstrap.Admin.Pages.Components var success = BindConverter.TryConvertTo(value, CultureInfo.CurrentCulture, out var parsedValue); if (success) { - result = parsedValue; + result = parsedValue!; validationErrorMessage = null; return true; } else { -#nullable disable result = default; -#nullable restore validationErrorMessage = $"The {FieldIdentifier.FieldName} field is not valid."; return false; } } else if (typeof(TItem).IsValueType) { - result = (TItem)Convert.ChangeType(value, typeof(TItem)); + result = (TItem)Convert.ChangeType(value, typeof(TItem))!; validationErrorMessage = null; return true; } diff --git a/src/admin/Bootstrap.Admin/Pages/Extensions/HttpContextExtensions.cs b/src/admin/Bootstrap.Admin/Pages/Extensions/HttpContextExtensions.cs index 44ba4537..68438dd3 100644 --- a/src/admin/Bootstrap.Admin/Pages/Extensions/HttpContextExtensions.cs +++ b/src/admin/Bootstrap.Admin/Pages/Extensions/HttpContextExtensions.cs @@ -1,4 +1,4 @@ -using Bootstrap.DataAccess; +using Bootstrap.DataAccess; using Longbow.Cache; using Longbow.Web; using Microsoft.Extensions.DependencyInjection; @@ -38,7 +38,7 @@ namespace Microsoft.AspNetCore.Http { UserAgent = agent, ConnectionId = key, - Ip = context.Connection.RemoteIpAddress.ToIPv4String(), + Ip = context.Connection.RemoteIpAddress?.ToIPv4String() ?? string.Empty, Browser = userAgent == null ? "Unknown" : $"{userAgent.Browser?.Name} {userAgent.Browser?.Version}", OS = userAgent == null ? "Unknown" : $"{userAgent.OS?.Name} {userAgent.OS?.Version}", FirstAccessTime = DateTime.Now, diff --git a/src/admin/Bootstrap.Admin/Pages/Extensions/JSRuntimeExtensions.cs b/src/admin/Bootstrap.Admin/Pages/Extensions/JSRuntimeExtensions.cs index 7268c133..85926264 100644 --- a/src/admin/Bootstrap.Admin/Pages/Extensions/JSRuntimeExtensions.cs +++ b/src/admin/Bootstrap.Admin/Pages/Extensions/JSRuntimeExtensions.cs @@ -45,14 +45,14 @@ namespace Microsoft.JSInterop /// 启用动画 /// /// - public static void InitDocument(this IJSRuntime? jSRuntime) => jSRuntime.InvokeVoidAsync("$.initDocument"); + public static void InitDocument(this IJSRuntime? jSRuntime) => jSRuntime?.InvokeVoidAsync("$.initDocument"); /// /// 弹出 Modal 组件 /// /// /// - public static void ToggleModal(this IJSRuntime? jSRuntime, string modalId) => jSRuntime.InvokeVoidAsync("$.toggleModal", modalId); + public static void ToggleModal(this IJSRuntime? jSRuntime, string modalId) => jSRuntime?.InvokeVoidAsync("$.toggleModal", modalId); /// /// 弹出 Toast 组件 @@ -61,7 +61,7 @@ namespace Microsoft.JSInterop /// /// /// - public static void ShowToast(this IJSRuntime? jSRuntime, string title, string message, ToastCategory cate) => jSRuntime.InvokeVoidAsync("$.showToast", title, message, cate.ToString()); + public static void ShowToast(this IJSRuntime? jSRuntime, string title, string message, ToastCategory cate) => jSRuntime?.InvokeVoidAsync("$.showToast", title, message, cate.ToString()); /// /// 弹出 Tooltip 组件 @@ -69,14 +69,14 @@ namespace Microsoft.JSInterop /// /// /// - public static void Tooltip(this IJSRuntime? jSRuntime, string id, string method) => jSRuntime.InvokeVoidAsync("$.tooltip", $"#{id}", method); + public static void Tooltip(this IJSRuntime? jSRuntime, string id, string method) => jSRuntime?.InvokeVoidAsync("$.tooltip", $"#{id}", method); /// /// 显示或者隐藏 网站 Blazor 挂件图标 /// /// /// - public static void ToggleBlazor(this IJSRuntime? jSRuntime, bool show) => jSRuntime.InvokeVoidAsync("$.toggleBlazor", show); + public static void ToggleBlazor(this IJSRuntime? jSRuntime, bool show) => jSRuntime?.InvokeVoidAsync("$.toggleBlazor", show); /// /// 显示或者隐藏 网站 Blazor 挂件图标 @@ -85,7 +85,7 @@ namespace Microsoft.JSInterop /// /// /// - public static void SetWebSettings(this IJSRuntime? jSRuntime, bool showSidebar, bool showCardTitle, bool fixedTableHeader) => jSRuntime.InvokeVoidAsync("$.setWebSettings", showSidebar, showCardTitle, fixedTableHeader); + public static void SetWebSettings(this IJSRuntime? jSRuntime, bool showSidebar, bool showCardTitle, bool fixedTableHeader) => jSRuntime?.InvokeVoidAsync("$.setWebSettings", showSidebar, showCardTitle, fixedTableHeader); /// /// 初始化 Table 组件 @@ -93,6 +93,6 @@ namespace Microsoft.JSInterop /// /// /// - public static ValueTask InitTableAsync(this IJSRuntime? jSRuntime, string id, bool firstRender) => jSRuntime.InvokeVoidAsync("$.initTable", id, firstRender); + public static void InitTableAsync(this IJSRuntime? jSRuntime, string id, bool firstRender) => jSRuntime?.InvokeVoidAsync("$.initTable", id, firstRender); } } diff --git a/src/admin/Bootstrap.Admin/Pages/Shared/LgbInput.razor b/src/admin/Bootstrap.Admin/Pages/Shared/LgbInput.razor index f9845852..6287e95a 100644 --- a/src/admin/Bootstrap.Admin/Pages/Shared/LgbInput.razor +++ b/src/admin/Bootstrap.Admin/Pages/Shared/LgbInput.razor @@ -3,7 +3,7 @@
- + @ChildContent diff --git a/src/admin/Bootstrap.Admin/Pages/Views/Components/MenusBase.cs b/src/admin/Bootstrap.Admin/Pages/Views/Components/MenusBase.cs index 9823986e..c70a701d 100644 --- a/src/admin/Bootstrap.Admin/Pages/Views/Components/MenusBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Views/Components/MenusBase.cs @@ -99,7 +99,7 @@ namespace Bootstrap.Admin.Pages.Views.Admin.Components if (AuthenticationStateProvider != null) { var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); - UserName = state?.User.Identity.Name; + UserName = state?.User.Identity!.Name; } } diff --git a/src/admin/Bootstrap.Admin/Pages/Views/Components/NotificationsBase.cs b/src/admin/Bootstrap.Admin/Pages/Views/Components/NotificationsBase.cs index 7e7e2ab6..9fb8365e 100644 --- a/src/admin/Bootstrap.Admin/Pages/Views/Components/NotificationsBase.cs +++ b/src/admin/Bootstrap.Admin/Pages/Views/Components/NotificationsBase.cs @@ -1,4 +1,4 @@ -using Bootstrap.Admin.Pages.Components; +using Bootstrap.Admin.Pages.Components; using Bootstrap.DataAccess; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; @@ -42,7 +42,7 @@ namespace Bootstrap.Admin.Pages.Views.Admin.Components if (AuthenticationStateProvider != null) { var state = await AuthenticationStateProvider.GetAuthenticationStateAsync(); - UserName = state?.User.Identity.Name; + UserName = state?.User.Identity!.Name; } } diff --git a/src/admin/Bootstrap.Admin/Pages/Views/Index.razor b/src/admin/Bootstrap.Admin/Pages/Views/Index.razor index 37e21b35..6cbf6542 100644 --- a/src/admin/Bootstrap.Admin/Pages/Views/Index.razor +++ b/src/admin/Bootstrap.Admin/Pages/Views/Index.razor @@ -20,6 +20,6 @@ { var menus = DataAccess.MenuHelper.RetrieveAllMenus(Layout.UserName); var menu = menus.FirstOrDefault(menu => "/Pages/Admin/Index".Contains(menu.Url.ToBlazorMenuUrl(), StringComparison.OrdinalIgnoreCase)); - JSRuntime.ActiveMenu(menu.Id); + JSRuntime.ActiveMenu(menu!.Id); } }