我正在尝试获取自定义错误,而不是每当 url 有空路由参数时通常找不到 404 错误。
[HttpGet]
[Route("{routeParam1}/{routeParam2}/path/{routeParam3}", Name = "XYZ")]
[Produces("application/json")]
public async Task<IActionResult> XYZ(
[FromRoute] string routeParam1,
[FromRoute] string routeParam2,
[FromRoute] string routeParam3,
[FromQuery] string queryParam1,
[FromQuery] string queryParam2,
CancellationToken cancellationToken)
{
return new ObjectResult("ok") { StatusCode = 200 };
}
结果应该是
Request: /abc/xyz//routeParam2/path/routeParam3?queryParam1=p1&queryParam2=p2
Response: 422
{
"customCode": "1111",
"warning": "routeParam1 is required."
}
Request: /abc/xyz/routeParam1//path/routeParam3?queryParam1=p1&queryParam2=p2
Response: 422
{
"customCode": "2222",
"warning": "routeParam2 is required."
}
Request: /abc/xyz/routeParam1/routeParam2/path/?queryParam1=p1&queryParam2=p2
Response: 422
{
"customCode": "3333",
"warning": "routeParam3 is required."
}
好的,我想我有件事请告诉我是否有更好的方法
在程序/启动中(您可能需要安装 SYStem.Security.Permissions nuget 包)
app.UseRouting();
app.UseMiddleware<ValidateRouteParametersAttribute>();
public class ValidateRouteParametersAttribute : ActionFilterAttribute
{
private readonly RequestDelegate _next;
private static Regex _regexPattern = new Regex(".*\\/xyz\\/([^\\/]*)\\/([^\\/]*)\\/path\\/([^\\/]*)\\/?");
public ValidateRouteParametersAttribute(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context)
{
var requestPath = context.Request.Path;
var match = _regexPattern.Match(requestPath);
// Check if the request path matches the targeted endpoint
if (match.Success)
{
string value1 = match.Groups[1].Value;
string value2 = match.Groups[2].Value;
string value3 = match.Groups[3].Value;
if (string.IsNullOrEmpty(value1))
{
await HandleError(context, "1111", "routeParam1 is required.");
return;
}
if (string.IsNullOrEmpty(value2))
{
await HandleError(context, "2222", "routeParam2 is required.");
return;
}
if (string.IsNullOrEmpty(value3))
{
await HandleError(context, "3333", "routeParam3 is required.");
return;
}
}
await _next(context);
}
private async Task HandleError(HttpContext context, string customCode, string warning)
{
context.Response.StatusCode = 422;
context.Response.ContentType = "application/json";
await context.Response.WriteAsync(
Newtonsoft.Json.JsonConvert.SerializeObject(new { customCode, warning }));
}
}