Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OWIN Self host - hook into begin request, end request events

In ASP.NET OWIN self host, how do you hook into the BeginRequest, EndRequest, Application Start and Application End events since there is no need for Global.asax.cs?

like image 573
govin Avatar asked Nov 05 '14 04:11

govin


People also ask

What is OWIN Self host?

Open Web Interface for . NET (OWIN) defines an abstraction between . NET web servers and web applications. OWIN decouples the web application from the server, which makes OWIN ideal for self-hosting a web application in your own process, outside of IIS.

How does Owin startup work?

Every OWIN Application has a startup class where you specify components for the application pipeline. There are different ways you can connect your startup class with the runtime, depending on the hosting model you choose (OwinHost, IIS, and IIS-Express).

What is IAppBuilder in Owin?

There is an extension method IAppBuilder. Run() that adds a middleware with no next middleware to call. So, adding a middleware using this method will end the OWIN pipeline. Let's add this middleware registration at the end in the Startup class. app.Run(context =>

Is Kestrel a Owin?

Kestrel is just a host implementation. Its goal is to provide OWIN hosting support across many platforms.


2 Answers

Add a simple owin middleware at the start of the pipeline to handle begin and end request.

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

    public override async Task Invoke(IOwinContext context)
    {
        Debug.WriteLine("Begin Request");//Add begin request logic
        await Next.Invoke(context);
        Debug.WriteLine("End Request");//Add end request logic
    }
}
like image 129
Rajiv Avatar answered Oct 08 '22 00:10

Rajiv


In WebAPI you can use filters for that. You can override OnActionExecuting and OnActionExecuted. If you don't want to annotate every single controller, you can add your filter als a global filter:

GlobalConfiguration.Configuration.Filters.Add(new MyFilterAttribute());

As replacement for ApplicationStart you can execute your code in your OwinStartup class. I don't know whether there is something similar to ApplicationEnd.

like image 40
MichaelS Avatar answered Oct 07 '22 22:10

MichaelS