Lemon
Lemon

Reputation: 147

How can I do something before processing a request in Nancy 2.x?

I want to do some things in every request, no matter the Module or Route. How can I accomplish this in Nancy 2.x?

If found How to Intercept all Nancy requests and How do I capture all requests irrespective of verb or path, but they are only applicable for Nancy 1.x and the Documentation is out-of-date.

Upvotes: 3

Views: 487

Answers (2)

Palle Due
Palle Due

Reputation: 6292

As you say documentation is not updated and most of the resources you can find online are for version 1.x.

How to solve it depends a little bit on what you want to do. If you are not messing with the response you can override ApplicationStartUp in the bootstrapper like this:

protected override void ApplicationStartup(TinyIoCContainer container, IPipelines pipelines)
{
    pipelines.BeforeRequest.AddItemToEndOfPipeline((ctx) =>
    {
        Console.Out.WriteLine("Hit");
        return null;
    });
    base.ApplicationStartup(container, pipelines);
}

If you, on the other hand, need to meddle with the response and the headers you can do it in the constructor of your overridden NancyModule with your Get setup like this:

public InstrumentProgrammingNancyModule()
{
    //// Enable CORS. 
    After.AddItemToEndOfPipeline((ctx) =>
        {
            ctx.Response.WithHeader("Access-Control-Allow-Origin", "*") 
                .WithHeader("Access-Control-Allow-Methods", "GET"); 
        });

    Get("/" , _ =>
    {
        return somethingOrOther;
    });
    ....
}

Both of these solutions work with Nancy 2.0.

Upvotes: 2

Sifiso Shezi
Sifiso Shezi

Reputation: 486

You can try this :

 public class NewBootstrapper : DefaultNancyBootstrapper
 {
        protected override void RequestStartup(TinyIoCContainer container, IPipelines pipelines, NancyContext context)
        {
            //Your code here
            base.RequestStartup(container, pipelines, context);
        }
 }

Upvotes: 0

Related Questions