gpt4 book ai didi

C# DotNet 核心中间件包装响应

转载 作者:太空狗 更新时间:2023-10-30 00:48:22 26 4
gpt4 key购买 nike

我有一个简单的 Controller 操作,如下所示:

    public Task<IEnumerable<Data>> GetData()
{
IEnumerable<Data> data = new List<Data>();
return data;
}

我希望能够检查中间件中的返回值,这样 JSON 看起来像

{
"data": [
],
"apiVersion": "1.2",
"otherInfoHere": "here"
}

所以我的负载总是在 data 中。我知道我可以在 Controller 级别执行此操作,但我不想在每个 Action 上都执行此操作。我宁愿在中间件中一劳永逸。

这是我的中间件示例:

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*/);
}

有什么想法吗?

现在获得了值(value),但为时已晚

        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;
}

最佳答案

查看评论以了解您可以做什么来包装响应。

public async Task Invoke(HttpContext context) {
//Hold on to original body for downstream calls
Stream originalBody = context.Response.Body;
try {
string responseBody = null;
using (var memStream = new MemoryStream()) {
//Replace stream for upstream calls.
context.Response.Body = memStream;
//continue up the pipeline
await next(context);
//back from upstream call.
//memory stream now hold the response data
//reset position to read data stored in response stream
memStream.Position = 0;
responseBody = new StreamReader(memStream).ReadToEnd();
}//dispose of previous memory stream.
//lets convert responseBody to something we can use
var data = JsonConvert.DeserializeObject(responseBody);
//create your wrapper response and convert to JSON
var json = new BaseResponse() {
data = data,
apiVersion = "1.2",
otherInfoHere = "here"
}.toJson();
//convert json to a stream
var buffer = Encoding.UTF8.GetBytes(json);
using(var output = new MemoryStream(buffer)) {
await output.CopyToAsync(originalBody);
}//dispose of output stream
} finally {
//and finally, reset the stream for downstream calls
context.Response.Body = originalBody;
}
}

关于C# DotNet 核心中间件包装响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47181356/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com