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?
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.
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).
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 =>
Kestrel is just a host implementation. Its goal is to provide OWIN hosting support across many platforms.
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
}
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With