HttpContextExtensions
The HttpContextExtensions
class provides helper extension methods for HttpContext
in ASP.NET Core applications. These methods make it easy to detect devices, build URLs, check user authentication, and work with routes in a clean, reusable way.
Methods
IsMobileDevice
Signature:
public static bool IsMobileDevice(this HttpContext httpContext)
Description: Detects if the current request comes from a mobile device by checking the User-Agent
header against common mobile patterns.
Returns:true
if the request is from a mobile device; otherwise, false
.
Example:
if (HttpContext.IsMobileDevice()) {
// Serve mobile-specific content
}
GetAbsoluteRoute
Signature:
public static string GetAbsoluteRoute(this HttpContext httpContext, string relativeUrl)
Description: Combines the scheme, host, and given relative URL to build a complete absolute URL.
Returns: The fully qualified URL as a string.
Example:
var absoluteUrl = HttpContext.GetAbsoluteRoute("images/logo.png");
// e.g. https://example.com/images/logo.png
GetCurrentUrl
Signature:
public static string GetCurrentUrl(this HttpContext httpContext)
Description: Returns the full URL of the current request, including the scheme, host, path, and query string.
Returns: A string with the complete current URL.
Example:
var currentUrl = httpContext.GetCurrentUrl();
GetRouteValueOrDefault
Signature:
public static object GetRouteValueOrDefault(this HttpContext httpContext, string routeValueKey)
Description: Retrieves the value of a specific route parameter or null
if the key does not exist.
Returns: The route value if present; otherwise, null
.
Example:
var id = HttpContext.GetRouteValueOrDefault("id");
IsUserAuthenticated
Signature:
public static bool IsUserAuthenticated(this HttpContext httpContext)
Description: Checks whether the current request’s user is authenticated.
Returns:true
if the user is authenticated; otherwise, false
.
Example:
if (HttpContext.IsUserAuthenticated()) {
// Proceed with secure actions
}
IsCurrentPage
Signature:
public static bool IsCurrentPage(this HttpContext context, string action, string controller)
Description: Checks whether the current request matches a given controller and action name. Useful for navigation highlights or active page checks.
Returns:true
if the current request matches both the specified controller and action; otherwise, false
.
Example:
if (HttpContext.IsCurrentPage("Index", "Home")) {
// Mark navigation link as active
}