C#中创建统一API接口的实现方案
作者:老胖闲聊
在 C# 中创建统一 API 接口需要从架构设计、技术选型和代码实现等多个层面进行规划,本文给大家详细介绍了实现方案和完整示例代码,对大家的学习或工作有一定的帮助,需要的朋友可以参考下
一、技术选型与架构设计
框架选择
- ASP.NET Core (6.0+)
- RESTful API 规范
核心组件
- 统一响应格式:标准化 JSON 响应结构
- 全局异常处理:统一错误返回
- 版本控制:API 版本管理
- 认证授权:JWT Bearer 认证
- 数据验证:Model Validation
- 日志记录:Serilog 或内置 ILogger
- Swagger 文档:OpenAPI 规范支持
架构分层
API Layer (Controllers) ↓ Application Layer (Services) ↓ Domain Layer (Models, Interfaces) ↓ Infrastructure Layer (Repositories)
二、完整实现步骤
1. 创建项目
dotnet new webapi -n UnifiedApiDemo
2. 添加 NuGet 包
dotnet add package Microsoft.AspNetCore.Mvc.Versioning dotnet add package Swashbuckle.AspNetCore dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
三、核心代码实现
1. 统一响应模型
public class ApiResponse<T>
{
public int Code { get; set; }
public string Message { get; set; }
public T Data { get; set; }
public DateTime Timestamp { get; } = DateTime.UtcNow;
public static ApiResponse<T> Success(T data) => new()
{
Code = 200,
Message = "Success",
Data = data
};
public static ApiResponse<object> Error(int code, string message) => new()
{
Code = code,
Message = message
};
}
2. 全局异常处理中间件
public class ExceptionMiddleware
{
private readonly RequestDelegate _next;
private readonly ILogger<ExceptionMiddleware> _logger;
public ExceptionMiddleware(RequestDelegate next, ILogger<ExceptionMiddleware> logger)
{
_next = next;
_logger = logger;
}
public async Task InvokeAsync(HttpContext context)
{
try
{
await _next(context);
}
catch (Exception ex)
{
_logger.LogError(ex, "Global exception occurred");
await HandleExceptionAsync(context, ex);
}
}
private static Task HandleExceptionAsync(HttpContext context, Exception exception)
{
context.Response.ContentType = "application/json";
context.Response.StatusCode = exception switch
{
ValidationException => StatusCodes.Status400BadRequest,
UnauthorizedAccessException => StatusCodes.Status401Unauthorized,
_ => StatusCodes.Status500InternalServerError
};
return context.Response.WriteAsJsonAsync(ApiResponse<object>.Error(
context.Response.StatusCode,
exception.Message
));
}
}
3. 统一响应包装过滤器
public class ApiResponseFilter : IAsyncResultFilter
{
public async Task OnResultExecutionAsync(
ResultExecutingContext context,
ResultExecutionDelegate next)
{
if (context.Result is ObjectResult objResult)
{
var apiResponse = ApiResponse<object>.Success(objResult.Value);
context.Result = new ObjectResult(apiResponse)
{
StatusCode = objResult.StatusCode
};
}
await next();
}
}
4. 配置服务(Program.cs)
var builder = WebApplication.CreateBuilder(args);
// 添加版本控制
builder.Services.AddApiVersioning(options =>
{
options.DefaultApiVersion = new ApiVersion(1, 0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
});
// 配置 Swagger
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Unified API", Version = "v1" });
});
// 添加统一响应过滤器
builder.Services.AddControllers(options =>
{
options.Filters.Add<ApiResponseFilter>();
});
// 配置 JWT 认证
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = "your_issuer",
ValidateAudience = true,
ValidAudience = "your_audience",
ValidateLifetime = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key"))
};
});
var app = builder.Build();
// 中间件管道
app.UseSwagger();
app.UseSwaggerUI();
app.UseMiddleware<ExceptionMiddleware>();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
5. 控制器示例(带版本控制)
[ApiController]
[Route("api/v{version:apiVersion}/[controller]")]
[ApiVersion("1.0")]
[Authorize]
public class ProductsController : ControllerBase
{
[HttpGet("{id}")]
[ProducesResponseType(typeof(ProductDto), 200)]
public IActionResult GetProduct(int id)
{
var product = new ProductDto { Id = id, Name = "Sample Product" };
return Ok(product);
}
[HttpPost]
[ValidateModel]
public IActionResult CreateProduct([FromBody] ProductCreateDto dto)
{
// 业务逻辑
return CreatedAtAction(nameof(GetProduct), new { id = 1 }, null);
}
}
6. 模型验证示例
public class ProductCreateDto
{
[Required]
[StringLength(100)]
public string Name { get; set; }
[Range(0, 10000)]
public decimal Price { get; set; }
}
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (!context.ModelState.IsValid)
{
var errors = context.ModelState
.Where(e => e.Value.Errors.Count > 0)
.ToDictionary(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
context.Result = new BadRequestObjectResult(
ApiResponse<object>.Error(400, "Validation Error", errors)
);
}
}
}
四、运行效果示例
成功响应
{
"code": 200,
"message": "Success",
"data": {
"id": 1,
"name": "Sample Product"
},
"timestamp": "2024-02-20T12:34:56Z"
}
错误响应
{
"code": 400,
"message": "Validation Error",
"data": {
"Price": ["The field Price must be between 0 and 10000."]
},
"timestamp": "2024-02-20T12:35:10Z"
}
五、扩展建议
- 性能优化:添加响应缓存机制
- 监控:集成 Application Insights
- 限流:使用 AspNetCoreRateLimit
- DTO 映射:使用 AutoMapper
- 单元测试:使用 xUnit/MSTest
此方案提供了从基础设施到业务逻辑的完整统一 API 实现框架,可根据具体需求进行扩展调整。
到此这篇关于C#中创建统一API接口的实现方案的文章就介绍到这了,更多相关C#创建统一API接口内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
