Where to implement Global.asax methods - c#

I am working on an ASP.Net application and currently the Global.asax contains the usual 5 methods:
Application_Start
Application_End
Session_Start
Session_End
Application_Error
However, I needed to implement the Application_AuthenticateRequest method as well, which is not a problem, I have just added it in Global.asax but in an another application I have seen this method being implemented elsewhere in another class which implements the IHttpModule interface.
How is this possible? The same app does not have the Application_AuthenticateRequest in Global.asax, their Global.asax looks like this:
void Application_BeginRequest(object sender, EventArgs e)
{
myConfig.Init();
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
myConfig.Init();
if (InstallerHelper.ConnectionStringIsSet())
{
//initialize IoC
IoC.InitializeWith(new DependencyResolverFactory());
//initialize task manager
TaskManager.Instance.Initialize(NopConfig.ScheduleTasks);
TaskManager.Instance.Start();
}
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
if (InstallerHelper.ConnectionStringIsSet())
{
TaskManager.Instance.Stop();
}
}
What makes the Application_AuthenticateRequest method run?

I would first recommend you read about HTTP handlers and modules in ASP.NET. Then you will know that in an ASP.NET application you could have multiple modules registered which will run for every request and you have the possibility to subscribe to different events of the request lifecycle, the same way you could do it in Global.asax. The advantage of this approach is that you could put the modules into a reusable assembly that you use in multiple applications and which avoids you the need to repeat the same code over and over again.

Basically the example I have been looking at created their own HTTP module and registered it in the web.config file:
They have created a new HTTP module like this:
public class MembershipHttpModule : IHttpModule
{
public void Application_AuthenticateRequest(object sender, EventArgs e)
{
// Fires upon attempting to authenticate the user
...
}
public void Dispose()
{
}
public void Init(HttpApplication application)
{
application.AuthenticateRequest += new EventHandler(this.Application_AuthenticateRequest);
}
}
also added the below to the web.config file:
<httpModules>
<add name="MembershipHttpModule" type="MembershipHttpModule, App_Code"/>
</httpModules>
As explained in the #Darin Dimitrov's link above: Modules must be registered to receive notifications from the request pipeline. The most common way to register an HTTP module is in the application's Web.config file. In IIS 7.0, the unified request pipeline also enables you to register a module in other ways, which includes through IIS Manager and through the Appcmd.exe command-line tool.

Related

How to add headers to a HttpActionContext response without short-circuiting the pipeline

I am writing a basic authentication Http filter for my ASP.NET application.
As part of the authentication, I need to add a header to the response. When my filter is called, the actioncontext.Response is null. If I create the response, I can add my headers, but it then short-circuits the pipeline, and the actual controller function is never called.
Should I be using a different way to implement my authorisation?
Please use Global AuthenticateRequest and PreSendRequestHeaders event to update response:
public class Global : HttpApplication
{
// The AuthenticateRequest event signals that the configured authentication mechanism has authenticated the current request.
// Subscribing to the AuthenticateRequest event ensures that the request will be authenticated before processing the attached module or event handler.
public void Application_AuthenticateRequest(object sender, EventArgs e)
{
// your authenticate code
}
public void Application_PreSendRequestHeaders(object sender, EventArgs e)
{
// your add heard code
}
}

How do I make Umbraco play nice with NWebSec's built in CSP Report event handler?

I'm working on a website which uses the Umbraco CMS version 7. I'm using NWebSec to implement a CSP header on the website. NWebSec has built in functionality to raise a .Net event when there's a CSP violation. Normally you'd catch that event with something like this:
protected void NWebSecHttpHeaderSecurityModule_CspViolationReported(object sender, CspViolationReportEventArgs e)
{
var report = e.ViolationReport;
var serializedReport = JsonConvert.SerializeObject(report.Details);
// Do a thing with the report
}
in the Global.asax.cs file. But so far as I can tell, Umbraco preempts the Global.asax.cs file, and it eats any event that's thrown. I have a file with a few custom event handlers like:
public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
to handle the standard pieces of application startup code that would normally be in the Global.asax.cs file, but putting the NWebSec event handler in that same file doens't work. Presumably it's because it's using the .Net event handler syntax rather than whatever Umbraco replaces it with.
How do I access the events thrown by NWebSec?
the Global.asax class inherits from UmbracoApplication so no, you can't use that. There are a number of reasons for this including enabling the ability to "run" Umbraco outside of the web context - i.e. in a console application).
After reviewing the available documentation on the NWebSec documentation website, I don't think you can just place your NWebSecHttpHeaderSecurityModule_CspViolationReported event handler method in the class, you will need to wire it up as well. It should probably look something like this:
public class MyGlobalEventHandler : ApplicationEventHandler {
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
var nWebSecHttpHeaderSecurityModule = umbracoApplication.Modules["NWebSecHttpHeaderSecurityModule"] as HttpHeaderSecurityModule;
if (nWebSecHttpHeaderSecurityModule != null) {
nWebSecHttpHeaderSecurityModule.CspViolationReported += NWebSecHttpHeaderSecurityModule_CspViolationReported;
}
base.ApplicationStarted(umbracoApplication, applicationContext);
}
protected void NWebSecHttpHeaderSecurityModule_CspViolationReported(object sender, CspViolationReportEventArgs e)
{
var report = e.ViolationReport;
var serializedReport = JsonConvert.SerializeObject(report.Details);
// Do a thing with the report
}
}
If you're using a newer version of Umbraco that supports OWIN (7.3.0), you could use the NWebsec.Owin library which may give you a better result and more flexibility perhaps.

Global.asax magic functions

When creating an ASP.NET Mvc project in Visual Studio, a Global.asax & Global.asax.cs will be created. In this .cs file you will find the standard Application_Start method.
My question is the following, how is this function called? because it is not a override. So my guess is that this method name is by convention. The same goes for the Application_Error method.
I want to know where these methods are hooked. Because I write those methods (not override them) I couldn't find any documentation on them in MSDN. (I found this page but it only tells you to hook to the Error event and shows a Application_Error(object sender, EventArgs e) but not how the Event and the method are linked.)
//Magicly called at startup
protected void Application_Start()
{
//Omitted
}
//Magicly linked with the Error event
protected void Application_Error(object sender, EventArgs e)
{
//Omitted
}
It isn't really magical.. the ASP.NET Pipeline wires all of this up.
You can see the documentation regarding this here.
Specifically you will be interested in the parts below:
An HttpApplication object is assigned to the request.
Which consists of a list of events that are fired and in what order.
There are links all over that page (too many to contain here) that link off to various other pages with even more information.
ASP.NET automatically binds application events to handlers in the
Global.asax file using the naming convention Application_event, such
as Application_BeginRequest. This is similar to the way that ASP.NET
page methods are automatically bound to events, such as the page's
Page_Load event.
Source: http://msdn.microsoft.com/en-us/library/ms178473.aspx
To demystify the 'magic' of the accepted answer, the ASP.Net pipeline is automagically binding the HttpApplication events to the methods with the Application_EventName in the class. If (much like me) you would rather see the events explicitly bound to a handler these can be bound by overriding HttpApplication.Init() and Visual Studio will generate the handler method with the correct signature.
public override void Init()
{
this.BeginRequest += MvcAppliction_BeginRequest;
}
private void MvcApplication_BeginRequest(object sender, EventArgs e)
{
...
}
There is an example of this method of binding events
ASP.Net itself creates it. Here is the flow as per MSDN -
User requests an application resource from the Web server.
ASP.NET receives the first request for the application.
ASP.NET core objects are created for each request.
An HttpApplication object is assigned to the request. In this step Global.asax will be processed and events will be associated automatically.
The request is processed by the HttpApplication pipeline. In this step the HttpApplication Global events are raised.
Here is the reference - ASP.Net Application Life Cycle.
From the reference - ASP.NET automatically binds application events to handlers in the Global.asax file using the naming convention Application_event, such as Application_BeginRequest.

Add Application Start event handler manually in constructor

In Global, as an alternative to the application AutoEventWireups, it seems that events are exposed for most of the underlying Application events (BeginRequest, AuthorizeRequest, Error, etc), as well as a set of asynch methods like AddOnBeginRequestAsync etc. However, I cannot find an equivalent event for ApplicationStart!
So my question is, is there anyway to subscribe to the 'same' event that the AutoEventWireup method Application_(On)Start is hooked into?
public class Global : HttpApplication
{
public Global()
{
// I can do this ...
base.BeginRequest += new EventHandler(Global_BeginRequest);
// Or even AddOnBeginRequestAsync();
// But how can I do this?
base.ApplicationStart += new EventHandler(GlobalApplication_Start);
}
protected void Global_BeginRequest(object sender, EventArgs e)
{
// ...
}
protected void Global_ApplicationStart(object sender, EventArgs e)
{
// ...
}
}
(Out of interest ... is there a way to switch off the AutoEventWireups in Global.asax?. Using the AutoEventWireup = "false" attribute only seems to work on aspx pages)
Edit - it seems that ApplicationStart and ApplicationEnd "are special methods that do not represent HttpApplication events". So I might be barking up the wrong tree entirely.
Edit
Re : Why would I need this? Unfortunately, a corporate customer has a framework in place whereby new apps need to inherit their custom HttpApplication class, and FWR, their HttpApplication had already implemented the autowireup Application_(On)Start, meaning that I needed to find another way to override the Framework wireup, so that I can Bootstrap my IoC container and Automapper maps. As per Lloyd's answer, I could also bootstrap in the ctor or Init() as well, although this isn't quite the same. Ultimately I was able to change the corporate framework to allow multiple subscriptions.
You could override Init:
public class MyApplication : HttpApplication
{
public override void Init()
{
base.Init();
}
}
However your constructor could also work just as well.
Be really careful with the Init method.
Using Init method for code that you want to be executed once in the Application lifecycle is a bad option as the Init method is called once for every instance of the HttpApplication...
As you said ApplicationStart and ApplicationEnd are special methods that do not represent HttpApplication events but they work in a similar fashion to the Page events when the AutoEventWireups is set to true..
After jumping to the .NET source code i found that the HttpApplicationFactory class looks for a method named "Application_OnStart" or "Application_Start" in the Global.asax file and then invokes it using reflection => ReflectOnMethodInfoIfItLooksLikeEventHandler().
Check out my question about a similar subject: HttpApplication.Start event does not exist

HttpModule and WCF (AspNetCompatibilityRequirementsMode.Allowed)

I'm hosting WCF services in Asp.net web page in ASP.NET Compatibility Mode
(AspNetCompatibilityRequirementsMode.Allowed). I've written simple HttpModule:
public class ExceptionInterceptor : IHttpModule
{
public ExceptionInterceptor()
{
}
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.Error += new EventHandler(context_Error);
}
void context_Error(object sender, EventArgs e)
{
// do something
}
}
web.config:
<httpModules>
<add name="ExceptionInterceptor" type="HttpModules.ExceptionInterceptor, HttpModules"/>
</httpModules>
My question is, why after occurence of unhandled exception in service, the code do not enter in context_Error(object sender, EventArgs e) function in my module.
What's more, the code do not even enter the Application_Error(object sender, EventArgs e) in Globals.asax.
Can someone explain that to me ?
What is the best option for global exception handling in WCF services ?
Regards
WCF is not ASP.NET - it might be able to use some of ASP.NET's infrastructure, but it's not ASP.NET per se.
In order to handle errors in a WCF service globally, you need to implement the IErrorHandler interface on your service - or plug in a WCF behavior that does this for you.
Check out the MSDN documentation on IErrorHandler - it's quite a simple interface, really. The HandleError method is typically used to log the error on the server to keep track of what's going on, while the ProvideFault method is used to turn the .NET exception on the server into an interoperable SOAP fault to send that back to the calling client (which might be a non-.NET client that can't really deal with a .NET-specific exception).
Rory Primrose has a great blog post about how to package up the IErrorHandler into a WCF service behavior which you can easily add to an existing service just in config - pretty close to magic :-) Also, check out another great post on the topic by Steve Barbour.

Categories