【问题标题】:Custom error objects for .Net Core 3 web api.Net Core 3 web api 的自定义错误对象
【发布时间】:2020-09-01 01:40:22
【问题描述】:

我目前正在.NET Core 3 中开发一个 web api。我目前有以下模型用于我的错误响应对象:

public class ErrorRo
{
    public string Message { get; set; }
    public int StatusCode { get; set; }
    public string Endpoint { get; set; }
    public string Parameters { get; set; }
    public string IpAddress { get; set; }
}

这是我需要实施的强制性回应,管理层已推动这一点。它允许人们访问我们的 API 时获得更详细的错误消息,以便他们知道出了什么问题。

目前我正在方法本身中手动填充此对象。有没有办法可以覆盖响应方法。 IE。我可以覆盖IActionResultBadRequest 以自动填充这些字段吗?

谢谢!

【问题讨论】:

  • 有很多可能的方法来实现这一点。一个自定义的middlewareAction Filters,一个简单的静态方法手动调用响应...
  • 你应该看看 ActionFilters/ResultFilters。这可能取决于您使用什么信息来填充所说的 dto。虽然可能创建一个具有新 OurBadRequest 方法的新控制器子类并改为调用它会更容易

标签: c# .net-core


【解决方案1】:

这取决于场景,但一种可能的方法是使用中间件,使用类似于this question 中描述的策略,以便您使用额外信息完成响应。

【讨论】:

    【解决方案2】:

    您可以为此目的使用result filters。添加一个过滤器,在返回结果之前替换结果

    型号

    public class CustomErroModel
    {
        public string Message { get; set; }
        public int StatusCode { get; set; }
        public string Endpoint { get; set; }
        public string Parameters { get; set; }
        public string IpAddress { get; set; }
    }
    

    过滤器

    public class BadRequestCustomErrorFilterAttribute : ResultFilterAttribute
    {
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //todo: check for BadRequestObjectResult if anything is returned for bad request
            if (context.Result is BadRequestResult) 
            {
                var result = new CustomErroModel
                {
                    StatusCode = 200, //you status code
                    Endpoint = context.HttpContext.Request.GetDisplayUrl(),
                    Message = "some message",
                    IpAddress = context.HttpContext.Connection.RemoteIpAddress.ToString(), //find better implementation in case of proxy
                    //this returns only parameters that controller expects but not those are not defined in model
                    Parameters = string.Join(", ", context.ModelState.Select(v => $"{v.Key}={v.Value.AttemptedValue}"))
                };
                
                context.Result = new OkObjectResult(result); // or any other ObjectResult
            }
        }
    }
    

    然后按操作或全局应用过滤器

    [BadRequestCustomErrorFilter]
    public IActionResult SomeAction(SomeModel model)
    

    services
        .AddMvc(options =>
        {
            options.Filters.Add<BadRequestCustomErrorFilterAttribute>();
            //...
        }
    

    【讨论】:

      猜你喜欢
      • 2019-07-23
      • 1970-01-01
      • 2013-04-21
      • 1970-01-01
      • 1970-01-01
      • 2019-05-14
      • 2021-11-27
      • 1970-01-01
      相关资源
      最近更新 更多