3

I have the below code in my OWIN Startup class:

myiapbuilder.Map("/something/something", doit =>
{
    doit.Use<pipepart1>();
    doit.Use<pipepart2>();
    doit.Use<piprpart3>();
});

If a condition occurs that I don't like in pipepart1, I would like to write a custom text/plain response to the caller within that Middleware, and do not fire pipepart2 or pipepart3. The BranchingPipelines sample on CodePlex shows lots of stuff, but not that.

Is it possible to short-circut a flow or otherwise stop OWIN processing of Middleware based on an earlier Middleware evaluation?

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
Snowy
  • 5,942
  • 19
  • 65
  • 119

1 Answers1

5

if you plan to respond directly to the client from pipepart1, then you could avoid calling other middlewares in the pipeline. Following is an example. Is this something you had in mind?

Here based on some condition (in my case if querystring has a particular key), I decide to either respond directly to the client or call onto next middleware.

appBuilder.Map("/something/something", doit =>
{
    doit.Use<Pipepart1>();
    doit.Use<Pipepart2>();
});

public class Pipepart1 : OwinMiddleware
{
    public Pipepart1(OwinMiddleware next) : base(next) { }

    public override Task Invoke(IOwinContext context)
    {
        if (context.Request.Uri.Query.Contains("shortcircuit"))
        {
            return context.Response.WriteAsync("Hello from Pipepart1");
        }

        return Next.Invoke(context);
    }
}

public class Pipepart2 : OwinMiddleware
{
    public Pipepart2(OwinMiddleware next) : base(next) { }

    public override Task Invoke(IOwinContext context)
    {
        return context.Response.WriteAsync("Hello from Pipepart2");
    }
}
Kiran
  • 56,921
  • 15
  • 176
  • 161
  • Super cool. Do you know of a friction-free way to integration test or unit test that without having to fire up the OWIN host runtime? – Snowy Sep 24 '13 at 14:03
  • Microsoft.Owin.Testing package has a TestServer which many people use to unit test OWIN application. This is an in memory server which takes in an Action (your Configuration method) and run a OWIN server without actually starting http listener and without touching the wire. Note: This is still in pre-release though. – Praburaj Sep 24 '13 at 15:05
  • var server = TestServer.Create(YourConfigMethod); var httpResponse = server.WithPath("/").SendAsync("GET") is an example usage of this TestServer. – Praburaj Sep 24 '13 at 15:06