You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Blazor Server中如何在服务类内控制前端显示重复提示信息

解决Blazor Server分类重复提示问题

方案一:自定义异常处理

通过在服务类中抛出自定义异常,Razor页面捕获后直接设置提示信息,判断逻辑完全保留在服务层:

  1. 定义自定义异常类(可放在服务所在程序集):
public class DuplicateCategoryException : Exception
{
    public DuplicateCategoryException(string message) : base(message)
    {
    }
}
  1. 修改服务类的Add方法:
public async Task<Category> Add(string categoryName)
{
    if (_context.Category.Any(c => c.Name == categoryName))
    {
        throw new DuplicateCategoryException("Already exists");
    }
    
    var cat = new Category { Name = categoryName };
    await _context.AddAsync(cat);
    await _context.SaveChangesAsync();
    return cat;
}
  1. 修改Razor页面的调用方法:
protected async Task IncrementCount()
{
    try
    {
        category = await _categoryService.Add("test");
        errorMessage = string.Empty;
    }
    catch (DuplicateCategoryException ex)
    {
        errorMessage = ex.Message;
        category = null;
    }
}

方案二:返回包含结果和错误的DTO

创建专用数据传输对象,让服务直接返回操作结果与错误信息,前端无需自行判断空值:

  1. 定义DTO类:
public class CategoryOperationResult
{
    public Category Category { get; set; }
    public string ErrorMessage { get; set; } = string.Empty;
    public bool IsSuccess => string.IsNullOrEmpty(ErrorMessage);
}
  1. 修改服务类的Add方法:
public async Task<CategoryOperationResult> Add(string categoryName)
{
    if (_context.Category.Any(c => c.Name == categoryName))
    {
        return new CategoryOperationResult { ErrorMessage = "Already exists" };
    }
    
    var cat = new Category { Name = categoryName };
    await _context.AddAsync(cat);
    await _context.SaveChangesAsync();
    return new CategoryOperationResult { Category = cat };
}
  1. 修改Razor页面的调用方法:
protected async Task IncrementCount()
{
    var result = await _categoryService.Add("test");
    category = result.Category;
    errorMessage = result.ErrorMessage;
}

两种方案均满足要求:重复判断逻辑完全保留在服务类中,前端仅需处理返回结果或捕获异常即可展示提示信息。

内容的提问来源于stack exchange,提问作者Manta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 07:47:04