1

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.

Matthias
  • 3,403
  • 8
  • 37
  • 50

1 Answers1

1

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.

Tratcher
  • 5,929
  • 34
  • 44
  • Ok, that's what I meant when I stated the `app.UseMapProxy()` method - it's just an extension. I just wondered if it should be a "real" middleware. Thanks for pointing this out. – Matthias Jun 10 '16 at 06:02
  • Just one more question: how would I implement a component that adds real per-request functionality, but also wants to use other middlewares? Extract the per-request stuff into a custom middleware and compose it with the other middlewares in an `IApplicationBuilder` extension? – Matthias Jun 10 '16 at 06:04