首页 > 解决方案 > 如何实现一个类来决定是好还是坏请求

问题描述

我正在寻找一种解决方案来改进我的代码。

我在所有控制器中都有以下代码:

var data = await _accountService.Create(value);
if (data.HasError)
{
    return BadRequest(data);
}
return Ok(data);

我正在寻找一个不需要执行此操作的解决方案,如果检查 HasError 是否存在。

在我的所有服务中,我返回以下课程:

public class ResponseEnvelope<T>
    {

        public T Result { get; set; }

        public IList<ErrorDto> Errors { get; set; }

        public IList<MessageDto> Messages { get; set; }

        public bool HasError
        {
            get
            {
                return Errors != null && Errors.Any();
            }
        }

        public bool HasMessage
        {
            get
            {
                return Messages != null && Messages.Any();
            }
        }

        public ResponseEnvelope<T> AddError(string code, string message = null, string description = null)
        {
            Errors.Add(new ErrorDto(code, message, description));
            return this;
        }
    }

标签: c#.netasp.net-core

解决方案


归档它的最佳方式是实现一个能够理解 API 响应的中间件。

因为我总是返回一个带有数据和错误(如果存在)的信封,所以中间件非常简单。

另外因为我有中间件,我能够实现单点日志。

public async Task Invoke(HttpContext context)
        {
            Stream originalBody = context.Response.Body;

            using (var memStream = new MemoryStream())
            {
                context.Response.Body = memStream;
                await _next(context);
                memStream.Position = 0;

                //get response body here after next.Invoke()
                var reader = new StreamReader(memStream);
                string responseBody = await reader.ReadToEndAsync();

                if (!string.IsNullOrEmpty(responseBody) && !responseBody.StartsWith("["))
                {
                    JObject json = JObject.Parse(responseBody);
                    if (json.ContainsKey("hasError") && (bool)json["hasError"] == true)
                    {
                        _logger.LogError($"{_correlationContext.CorrelationContext.CorrelationId} {responseBody}");
                        context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    }
                    else
                    {
                        if (context.Request.Path.Value.StartsWith("/api/authentication/users"))
                        {
                            _logger.LogInformation($"{_correlationContext.CorrelationContext.CorrelationId} Logged");
                        }
                        else
                        {
                            _logger.LogInformation($"{_correlationContext.CorrelationContext.CorrelationId} {responseBody}");
                        }
                    }
                }

                memStream.Position = 0;
                await memStream.CopyToAsync(originalBody);
                context.Response.Body = originalBody;

            }

推荐阅读