在空路由参数上创建自定义错误响应

问题描述 投票:0回答:1
  • 使用 .net 8 和默认的 .net core Web API 模板
  • 我无法更改路由路径,因此无法更改查询路由
  • 请求将如下所示(我给出了 3 个请求示例)

我正在尝试获取自定义错误,而不是每当 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."
 }
c# .net routes
1个回答
0
投票

好的,我想我有件事请告诉我是否有更好的方法

在程序/启动中(您可能需要安装 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 }));
}

}

© www.soinside.com 2019 - 2024. All rights reserved.