Saturday, May 2, 2015

ASP.Net C# Get Page Name With Optional Parameters To Include Extension And QueryString

Here's a simple static function that I keep in my utilities/functions class to let you easily get the the page name being requested.

Functions.cs
 public static string GetPageName(bool IncludeExtension = false, bool IncludeQueryString = false)  
 {  
    string AbsolutePath = HttpContext.Current.Request.Url.AbsolutePath;  
    string PageName = Path.GetFileName(AbsolutePath);  
    string Extension = Path.GetExtension(AbsolutePath);  
    string QueryString = HttpContext.Current.Request.QueryString.ToString();  
   
    if (!IncludeExtension && !IncludeQueryString && PageName.HasValue())  
    {  
       PageName = PageName.Replace(Extension, string.Empty);  
    }  
   
    if (IncludeQueryString && PageName.HasValue() && QueryString.HasValue())  
    {  
       PageName = string.Format("{0}?{1}", PageName, QueryString);  
    }  
   
    return PageName;  
 }  

The GetPageName function is dependent on the following extension methods, although it could easily be re-factored to check the string length directly; however, I prefer to use these types of extension methods throughout the projects to keep things consistent and concise.

Extensions.cs
 public static bool HasValue(this string Value)  
 {  
    return !Value.IsBlank();  
 }  
   
 public static bool IsBlank(this string Value)  
 {  
    bool ReturnValue = true;  
   
    if (Value != null)  
    {  
       ReturnValue = Value.Trim().Length == 0;  
    }  
   
    return ReturnValue;  
 }  

The GetPageName function is very basic but a nice way to get the page name, and optionally lets you indicate whether or not to include the extension in the page name, and whether you want to include the querystring parameters in the page name.

Example usage and output:
 string Url = Functions.GetPageName(IncludeExtension: true, IncludeQueryString: true);  
Test.aspx?x=1

Example usage and output:
 string Url = Functions.GetPageName(IncludeExtension: true, IncludeQueryString: false);  
Test.aspx

Example usage and output:
 string Url = Functions.GetPageName(IncludeExtension: false, IncludeQueryString: false);  
Test

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: