Sunday, December 11, 2016

ASP.Net C# Checking Request Header and/or Request Cookies in Global.asax Application_BeginRequest

Here is a simple example using C# to get a custom token from either the HTTP header or HTTP cookie on any page in your application. This example relies on a few custom extension methods that I regularly use, although they could be refactored out very easily.

In this particular example we're checking the Request.Headers collection first for a custom key named Token. If found we use it, if not found we check the Request.Cookies collection, and if found we use it.

Global.asax.cs
   protected void Application_BeginRequest(object sender, EventArgs e)
   {
      // variables
      string Token = string.Empty;

      // check for token in header
      if (Token.IsBlank() && Request.Headers.AllKeys.Any(k => k.IsEqual("Token")))
      {
         Token = Server.UrlDecode(Request.Headers.GetValues("Token").First());
      }

      // check for token in cookie
      if (Token.IsBlank() && Request.Cookies.AllKeys.Any(k => k.IsEqual("Token")))
      {
         Token = Server.UrlDecode(Request.Cookies.Get("Token").Value);
      }

      // if token specified try to parse it
      if (Token.HasValue())
      {
         // todo
      }

      // debug
      Response.Write("Application_BeginRequest<br />");
      Response.Write(string.Format("Token: {0}<br />", Token));
   }

The idea behind this example was to be able to let an encrypted authentication token be passed in to automatically authenticate the user for any page within the application. Having it check both the Request.Headers and the Request.Cookies collection provides some additional flexibility for the processes that pass in the token. For example, some older versions of Android code don't easily allow a custom HTTP header to be specified, but could easily set a cookie.

Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey

0 comments: