我有一个用Asp.Net Core编写的rest服务,该服务仅执行CRUD操作。前端(Angular和Native Mobile Apps)要求端点的响应采用以下格式:
{ “成功”:false, “消息”:null, “基准”:空 }
API中有很多控制器,由于我不想更改API中所有控制器的所有方法的所有返回逻辑,所以我写了一个中间件:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;
using System.IO;
using System.Threading.Tasks;
namespace HttpInterceptor.Classes
{
public class ResponseDatum
{
public bool IsSuccessful { get; set; }
public string Message { get; set; }
public object Datum { get; set; }
}
public class HttpMiddleware
{
private readonly RequestDelegate _next;
public HttpMiddleware(RequestDelegate next)
{
_next = next;
}
public async Task Invoke(HttpContext context, DbContext dbContext)
{
if (context.Response.StatusCode.Equals(200))
{
Stream originalBody = null;
using MemoryStream modifiedBody = new MemoryStream();
using StreamReader streamReader = new StreamReader(modifiedBody);
context.Response.OnStarting((state) =>
{
context.Response.ContentType = "application/json";
return Task.CompletedTask;
}, null);
originalBody = context.Response.Body;
context.Response.Body = modifiedBody;
await _next.Invoke(context);
modifiedBody.Seek(0, SeekOrigin.Begin);
string originalContent = streamReader.ReadToEnd();
context.Response.Body = originalBody;
await context.Response.WriteAsync(JsonConvert.SerializeObject(new ResponseDatum
{
Datum = JsonConvert.DeserializeObject(originalContent),
IsSuccessful = true
}));
}
else
{
await _next.Invoke(context);
return;
}
}
}
public static class HttpMiddlewareExtensions
{
public static IApplicationBuilder UseHttpMiddleware(this IApplicationBuilder builder)
{
return builder.UseMiddleware<HttpMiddleware>();
}
}
}
我想问的是,这种方法在我拦截每个请求时是否存在一些性能问题。有没有更好的方法来实现这一目标?像某种全局映射还是过滤器属性?