.NET 8.0 WebAPI: 我的
controller
:
[HttpGet("teacher/{source}/{id}"]
public async Task<ActionResult<Teacher?>> GetTeacher(TeacherEnumSource source, string id)
{
var result = await _teacherData.GetTeacher(source, id);
return result == null ? StatusCode(404, $"No Teacher found for Source: {source} and ID: {id}") : Ok(result);
}
注意
source
参数是 enum
:
public enum TeacherEnumSource
{
SCHOOL,
UNIVERSITY,
KINDERGARTEN
}
如果我将 bad param 作为不在
enum
列表中的源传递给我的 API,我会自动收到此错误,这有点不错:
{
"type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"errors": {
"source": [
"The value 'camping' is not valid."
]
},
"traceId": "00-4e2baa0235572f8359e0e15225fffd3e-4ccac5f22f8ede03-00"
}
如果我设置断点,它甚至不会运行
_teacherData.GetTeacher(source, id)
行,因此无需显示该代码。
我还没有添加错误处理,我什至注释掉了我的 program.cs
中的这两行以确保:
//app.UseStatusCodePages();
//app.UseExceptionHandler();
所以 who 正在为我做这个错误处理 更重要的是: 我如何对其进行一些自定义,因为我确实想将事件记录到我的外部记录器(在我的例子中是 DataDog)。
您应该选择使用
建模并使用模型验证器(发布而不是获取)
手动验证枚举值以测试该值是否有效
使用路由约束在路由中进行验证:
公共类 RangeConstraint : IRouteConstraint { 私有只读 int _min; 私有只读 int _max;
public RangeConstraint(int min, int max)
{
_min = min;
_max = max;
}
public bool Match(HttpContext httpContext, IRouter route, string routeKey, RouteValueDictionary values, RouteDirection routeDirection)
{
if (values.TryGetValue(routeKey, out var value) && int.TryParse(value.ToString(), out int intValue))
{
return intValue >= _min && intValue <= _max;
}
return false;
}
}
并使用以下方法进行集成:
services.Configure<RouteOptions>(options =>
{
options.ConstraintMap.Add("range", typeof(RangeConstraint));
});