Blazor WASM中封装带错误通知的API调用方案是否合理?
你的APIHelper方案合理性分析与优化建议
你的方案完全合理——通过抽离API请求的错误通知逻辑到统一服务中,解决了重复编写样板代码的问题,让组件代码更简洁易维护,完全符合DRY(Don't Repeat Yourself)原则。
不过现有代码还有几个可以优化的细节,能让逻辑更简洁高效:
可优化的点
- 避免重复实例化内部类:每次调用
GetConsentForms都新建HttpClientWithNotification实例完全没必要,把该类的方法改成静态,或直接把逻辑整合到APIHelper的泛型方法里更高效。 - 消除冗余参数传递:
APIHelper已经注入了HttpClient和NotificationService,但每次调用HttpGet还要手动传这两个参数,完全可以让内部逻辑直接使用外部类的实例字段,不用重复传参。 - 修正未使用的参数:
GetConsentForms方法里的Module参数目前没用到,检查下是不是URL里需要动态替换这个值(比如$"/api/v1/consent/forms/{Module}"),避免无效参数。 - 优化返回值初始化:
T? getResult = new();对于引用类型来说会创建空实例,但如果API返回null或请求失败抛出异常,这个初始化没有意义,直接初始化为null更合理。
优化后的代码示例
using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using NeuroCare.Shared.Models; using Radzen; using System.Net.Http.Json; namespace NeuroCare.BlazorWASM.Services { public class APIHelper { private readonly HttpClient _httpClient; private readonly NotificationService _notificationService; private const string url_getconsentforms_base = "/api/v1/consent/forms/"; public APIHelper(HttpClient httpClient, NotificationService notificationService) { _httpClient = httpClient; _notificationService = notificationService; } // 假设Module参数需要用于动态拼接URL public async Task<ConsentForms?> GetConsentForms(string module) { return await HttpGet<ConsentForms>($"{url_getconsentforms_base}{module}"); } // 泛型Get方法,统一处理请求与错误 private async Task<T?> HttpGet<T>(string url) { try { return await _httpClient.GetFromJsonAsync<T>(url); } catch (HttpRequestException e) { if (e.StatusCode == System.Net.HttpStatusCode.Unauthorized) { _notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Unauthorized", Detail = "You are not authorized to perform this action", Duration = 4000 }); } throw; } catch (AccessTokenNotAvailableException exception) { exception.Redirect(); return default; } catch (Exception e) { _notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Error, Summary = "Unexpected error", Detail = e.Message, Duration = 4000 }); throw; } } } }
额外建议
- 如果后续需要Post/Put/Delete等其他请求方法,同样可以在
APIHelper里添加对应的泛型方法,统一处理错误通知。 - 可以把错误提示的文案抽成常量,方便统一修改。
- 考虑添加请求加载状态的处理(比如配合Radzen的Loading组件),进一步提升用户体验。
内容的提问来源于stack exchange,提问作者RichC
相关产品推荐
相关产品推荐

