Using the Segment Feature
Source: Dev.to
Overview
The Segment attribute can be applied to ASPX pages. When enabled, any path parts that appear after the .aspx file are treated as segments and are routed to the same executing page. This feature gives you full control over URL paths without needing query strings.
Enabling Segment on a Page
...
Example Paths
If Segment is enabled on /page/about.aspx
/page/about.aspx/segment1/segment2/.../segmentN
The file /page/about.aspx is still executed, and the extra parts are available as segments.
If Segment is enabled on /page/about/Default.aspx
Both of the following URLs work:
/page/about/Default.aspx/segment1/segment2/.../segmentN
/page/about/segment1/segment2/.../segmentN
Accessing Segment Values
Segments are zero‑based indexed.
// Given URL: /page/about/segment1/segment2/segment3
Segment.GetValue(0) // returns "segment1"
Segment.GetValue(1) // returns "segment2"
Segment.GetValue(2) // returns "segment3"
In Views (Razor‑style)
segment 1 is: @Segment.GetValue(0)
segment 2 is: @Segment.GetValue(1)
In Classic ASPX Syntax
segment 1 is:
segment 2 is:
In Code‑Behind
using CodeBehind;
namespace YourProjectName
{
public partial class DefaultController : CodeBehindController
{
public void PageLoad(HttpContext context)
{
Write(Segment.GetValue(0));
Write(Segment.GetValue(1));
}
}
}
Checking Segment Existence
@if (!Segment.Exist(0))
{
Value does not exist
}
Interaction with MVC Routing
In the default MVC configuration, the Segment feature is automatically enabled for controller routing.
using CodeBehind;
public partial class User : CodeBehindController
{
public void PageLoad(HttpContext context)
{
// path: /user/{id}
Write(Segment.GetValue(0));
}
}
Rewrite ASPX File to Directory
The CodeBehind framework can rewrite an .aspx file path as a directory name. When the option is enabled, routes that omit the .aspx extension are treated as directory paths.
# CodeBehind options (do not change order)
rewrite_aspx_file_to_directory=true
Example
- Access
/page/contact.aspxas/page/contact - Segments can still be appended:
/page/contact/segment1/segment2/.../segmentN
Note: Enabling this rewrite does not add extra processing overhead.
Limitations
If Segment is enabled on a specific file, ASPX view files in its subdirectories are no longer reachable.
For instance, with Segment enabled on /page/about/Default.aspx, the path /page/about/license/Default.aspx becomes inaccessible.
Resources
- CodeBehind on GitHub:
- CodeBehind NuGet package:
- CodeBehind documentation page: