我有一个简单的控制器动作,看起来像:
public Task<IEnumerable<Data>> GetData()
{
IEnumerable<Data> data = new List<Data>();
return data;
}
我希望能够检查中间件中的返回值,使JSON看起来像
{
"data": [
],
"apiVersion": "1.2",
"otherInfoHere": "here"
}
所以我的有效载荷总是在
data
. 我知道我可以在控制器级别这样做,但我不想在每一个动作上都这样做。我宁愿在中间件中一劳永逸地完成它。
以下是我的中间件示例:
public class NormalResponseWrapper
{
private readonly RequestDelegate next;
public NormalResponseWrapper(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
var obj = context;
// DO something to get return value from obj
// Create payload and set data to return value
await context.Response.WriteAsync(/*RETURN NEW PAYLOAD HERE*/);
}
有什么想法吗?
现在已经得到了价值,但现在归还已经太晚了
try
{
using (var memStream = new MemoryStream())
{
context.Response.Body = memStream;
await next(context);
memStream.Position = 0;
object responseBody = new StreamReader(memStream).ReadToEnd();
memStream.Position = 0;
await memStream.CopyToAsync(originalBody);
// By now it is to late, above line sets the value that is going to be returned
await context.Response.WriteAsync(new BaseResponse() { data = responseBody }.toJson());
}
}
finally
{
context.Response.Body = originalBody;
}