【ASP.NET CORE】2.ORM仓储完善 添加Swagger

仓储

当插入数据时string类型主键的ID 为空时自动生成

//BaseRepository.cs

    public async Task<bool> AddAsync(T entity)
    {
        if (typeof(TKey) == typeof(string))
        {
            var currentId = entity.Id as string;
            if (string.IsNullOrWhiteSpace(currentId))
            {
                entity.Id = (TKey)(object)Guid.NewGuid().ToString("N");
            }
        }
    
        return await _db.Insertable(entity).ExecuteCommandAsync() > 0;
    }

自动路由更改

自动路由到方法名,防止Swagger生成接口文档失败

namespace WebApplication1.Application.Base;
[ApiController]
[Route("api/[controller]/[action]")]
public abstract class ApiControllerBase : ControllerBase
{
    protected IActionResult ApiResponse<T>(T data)
    {
        return Ok(new { success = true, data });
    }

    protected IActionResult ApiError(string message)
    {
        return BadRequest(new { success = false, error = message });
    }
}

Swagger

Appliction层引入Swagger包

dotnet add package Swashbuckle.AspNetCore

Program.cs 配置

var builder = WebApplication.CreateBuilder(args);

// 添加 Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

// ... 你的其他服务注册 ...

var app = builder.Build();

// 启用 Swagger
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

// ... 其他中间件 ...

app.Run();
© 版权声明
THE END
喜欢就支持一下吧
点赞13 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容