c# - 如何实现一个类来决定是好还是坏请求
问题描述
我正在寻找一种解决方案来改进我的代码。
我在所有控制器中都有以下代码:
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;
}
}
解决方案
归档它的最佳方式是实现一个能够理解 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;
}
推荐阅读
- python - 如何比较python中默认dict中列表的索引值
- airflow - 如何根据条件不在 DAG 中显示任务
- android - 如何从 android SERVICE 禁用/启用屏幕旋转?
- clojure - Clojure如何使用reducer实现map?
- rasa-nlu - Rasa 调度器提醒如何将消息返回给客户端,例如应用程序
- python - Django 和子进程:开发服务器在 signal.SIGTERM 上终止
- azure - 通过 Azure SQL 连接 Kentico
- python - DataFrame直方图分组并在同一图中
- python - 函数参数中的 Python 类型注释
- c++ - 如何使用索引命名变量以存储输入 mxArray?