Roadmap › ASP.NET Web Forms — Page Life Cycle, ViewState, Controls and State Management › Module: Application Configuration, Security and Errors
Lessons in this course (10)
9. Authentication, security and custom error handling in Web Forms
Intermediate★ Must knowLesson 9 of 10
- Windows authentication (intranet, Active Directory) or Forms authentication (login page + encrypted auth cookie,
FormsAuthentication.SetAuthCookie); later ASP.NET Identity (OWIN) replaced Membership providers. - Authorization in web.config
<authorization>per folder/page, or in codeUser.IsInRole("Admin"). - Built-in protections: request validation (blocks
<script>in input), ViewState MAC, event validation; still HTML-encode output (<%: %>,Server.HtmlEncode), use parameterised SQL, setViewStateUserKeyagainst CSRF,requireSSL,HttpOnlycookies.
Error handling levels (most specific first):
csharp
// 1. try/catch around risky code in the event handler
// 2. Page level
protected void Page_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
Logger.Error(ex, "Error on " + Request.Url);
Server.ClearError();
Response.Redirect("~/Error.aspx", false);
}
// 3. Application level — Global.asax Application_Error (logs everything unhandled)
// 4. web.config <customErrors> (ASP.NET) and <httpErrors> (IIS) — friendly pages, never show stack traces to userscustomErrors mode="On" shows custom pages to everyone; RemoteOnly shows details only on the server; Off shows the "yellow screen of death" — never in production. ELMAH or log4net/NLog/Serilog capture errors (see the Exception Handling and Logging courses).