














using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Threading.Tasks;
using Thea;
using Thea.ExceptionEx;
using Thea.Web;
public class TheaWebMiddleware
{
private readonly RequestDelegate next;
public TheaWebMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
// SignalR 放行
if (context.GetEndpoint()?.Metadata?.GetMetadata<SignalREndpointAttribute>() != null)
{
await next(context);
return;
}
CommonResponse result = null;
var statusCode = 200;
try
{
await next(context);
if (context.Response.StatusCode == 200)
{
if (context.Response.Body.Length != 0)
{
//有数据时直接返回
//当前代码没有处理通用结构,此处直接返回即可
//如果需要处理通用结构则需要在此处增加
return;
}
else
{
//无任何数据返回时返回通用的成功结构
result = CommonResponse.Success;
}
}
else
{
statusCode = context.Response.StatusCode;
result = CommonResponse.Fail(statusCode, statusCode.ToString());
}
}
catch (Exception ex)
{
var exception = ex.InnerException ?? ex;
result = BuildErrorResponse(exception, 200);
}
var json = JsonConvert.SerializeObject(result);
context.Response.Clear();
context.Response.StatusCode = statusCode;
await context.Response.WriteAsJsonAsync(json);
}
private static CommonResponse BuildErrorResponse(Exception exception, int statusCode)
{
if (exception is LevelException levelEx)
{
var exConfig = LevelExceptionConfig.GetConfig(levelEx);
return CommonResponse.Fail((int)ErrorLevel.LangageInfo, levelEx.Message, exConfig);
}
return CommonResponse.Fail(statusCode, exception.Message);
}
}
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。