Roadmap › ASP.NET Web Forms — Page Life Cycle, ViewState, Controls and State Management › Module: Application Configuration, Security and Errors
Lessons in this course (10)
8. Global.asax, web.config, HTTP modules and handlers
Intermediate★ Must knowLesson 8 of 10
csharp
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e) // once per app domain start
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Session_Start(object sender, EventArgs e) { } // new user session
protected void Application_BeginRequest(object sender, EventArgs e) { }
protected void Application_Error(object sender, EventArgs e) // unhandled exceptions — log here
{
var ex = Server.GetLastError();
Logger.Error(ex);
}
protected void Session_End(object sender, EventArgs e) { } // InProc session mode only
protected void Application_End(object sender, EventArgs e) { }
}xml
<configuration>
<connectionStrings>
<add name="Shop" connectionString="Server=.;Database=Shop;Integrated Security=true" providerName="System.Data.SqlClient" />
</connectionStrings>
<appSettings><add key="PageSize" value="20" /></appSettings>
<system.web>
<compilation debug="false" targetFramework="4.8" /> <!-- debug=false in production! -->
<httpRuntime targetFramework="4.8" maxRequestLength="10240" />
<authentication mode="Forms"><forms loginUrl="~/Account/Login.aspx" timeout="30" requireSSL="true" /></authentication>
<sessionState mode="InProc" timeout="20" />
<customErrors mode="RemoteOnly" defaultRedirect="~/Error.aspx">
<error statusCode="404" redirect="~/NotFound.aspx" />
</customErrors>
</system.web>
<location path="Admin">
<system.web><authorization><allow roles="Admin" /><deny users="*" /></authorization></system.web>
</location>
<system.webServer>
<modules><add name="AuditModule" type="ShopWeb.Infrastructure.AuditModule" /></modules>
<httpErrors errorMode="DetailedLocalOnly" />
</system.webServer>
</configuration>Config inheritance: machine.config → root web.config (Framework folder) → site web.config → sub-folder web.configs. Changing web.config restarts the application.
HTTP module (IHttpModule) — hooks pipeline events for every request (auth, logging, URL rewriting). HTTP handler (IHttpHandler) — produces the response for a request type (.aspx page handler, .ashx generic handler for files/images/JSON).
csharp
public class ThumbnailHandler : IHttpHandler // Thumbnail.ashx
{
public bool IsReusable => true;
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";
context.Response.BinaryWrite(ImageService.Thumbnail(context.Request.QueryString["id"]));
}
}