简体   繁体   English

.Net Core 3 web api 的自定义错误对象

[英]Custom error objects for .Net Core 3 web api

I am currently developing a web api in .NET Core 3. I currently have the following model for my error response object: I am currently developing a web api in .NET Core 3. I currently have the following model for my error response object:

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; }
}

This is a mandated response I need to implement, management has pushed this.这是我需要实施的强制性回应,管理层已经推动了这一点。 It allows more verbose error messages for people hitting our API so that they know what went wrong.它允许人们访问我们的 API 时获得更详细的错误消息,以便他们知道出了什么问题。

At the moment I am currently populating this object manually in the methods themselves.目前,我正在方法本身中手动填充此 object。 Is there a way where I can overwrite the response methods.有没有办法可以覆盖响应方法。 Ie can I override the BadRequest of IActionResult to automatically populate these fields?即我可以覆盖IActionResultBadRequest以自动填充这些字段吗?

Thanks!谢谢!

Well it depends on the scenario, but one possible approach could be to use a middleware using a similar strategy like the one described in this question , so that you complete the response with extra information.好吧,这取决于场景,但一种可能的方法是使用中间件,使用类似于此问题中描述的策略的策略,以便您使用额外信息完成响应。

You can use result filters for this purpose.您可以为此目的使用结果过滤器 Add a filter which repalces result before sending it back添加一个过滤器,在将结果发回之前替换结果

Model Model

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; }
}

Filter筛选

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
        }
    }
}

Then apply filter per action or globally然后按操作或全局应用过滤器

[BadRequestCustomErrorFilter]
public IActionResult SomeAction(SomeModel model)

or或者

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM