asp.net-coreasp.net-core-1.0owin-middleware

Middleware that calls other middlewares


I have some piece of ASP.NET Core code that I want to extract into a custom middleware. Specifically, the following logic should be implemented: when a certain path mapPath is requested, proxy the request to another host, identified by proxyUrl.

The following code in Startup.cs does the trick:

var proxyUri = new Uri(proxyUrl);
builder.Map(
    mapPath,
    appMapped =>
    {
        appMapped.RunProxy(
            new ProxyOptions
                {
                    Scheme = proxyUri.Scheme,
                    Host = proxyUri.Host,
                    Port = proxyUri.Port.ToString()
                });
    }
);

Well, it uses app.Map() to branch and then the Proxy middleware to proxy the request.

(How) Is it possible to extract this logic to a custom and resusable middleware? Or am I not able to use a "real" middleware here? What I can do is of course write an extension method, e.g. app.UseMapProxy() and put the logic 1:1 in there, but I just wondered if I can do it with a "real" middleware class as well.


Solution

  • This kind of setup is best encapsulated in an IApplicationBuilder extension method. You're not adding any per-request functionality beyond the existing components, just hooking them up together.