ASP.NET Core MVC 2.2 Batch Requests Middleware
Asked Answered
T

0

6

I would like a simple middleware that I can use to combine multiple requests into one request and return the result as a single array response.

I don't want to use OData because its too heavy, plus I don't like it.

I have no idea how I can split one HttpContext into multiple small internal sub HttpContext's.

This is my attempt:

    public static IApplicationBuilder BatchRequest(this IApplicationBuilder app)
    {
        app.Map("/api/batch", builder =>
        {
            builder.Use(async (context, next) =>
            {
                string[] paths = (context.Request.Query.Get("path") as StringValues?) ?? new string[] { };
                Stream originalBody = context.Response.Body;
                RecyclableMemoryStreamManager _recyclableMemoryStreamManager = new RecyclableMemoryStreamManager();

                IEnumerable<string> responses = await paths.SelectAsync(async path =>
                {
                    context.Request.Path = path;
                    MemoryStream newResponseBody = _recyclableMemoryStreamManager.GetStream();
                    context.Response.Body = newResponseBody;
                    await next.Invoke();
                    return RequestResponseLoggingMiddleware.ReadStreamInChunks(newResponseBody);
                });

                await context.Response.WriteAsync(responses.Serialize());
            });
        });

        return app;
    }

There is this example, but i am not yet sure how to use it: https://github.com/Tornhoof/HttpBatchHandler

Please be kind.

Toaster answered 11/12, 2018 at 22:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.