我有一个简单的控制器动作,看起来像这样:
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;
}