Most of popular websites have own mobile websites on their subdomain which is not so popular. Hence when mobile users go to main webpage should be redirected to their mobile site.
So we need to write a small piece of code in main webpage to detect whether the user is from mobile device.
If the user is detected to be from mobile, we can redirect to its corresponding mobile website.
The ASP.Net C# function to detect whether the request is from mobile device.
public static Boolean isMobile()
{
HttpContext curcontext = HttpContext.Current;
string user_agent = curcontext.Request.ServerVariables["HTTP_USER_AGENT"];
user_agent = user_agent.ToLower();
// Checks the user-agent
if (user_agent != null )
{
// Checks if its a Windows browser but not a Windows Mobile browser
if (user_agent.Contains("windows") && !user_agent.Contains("windows ce"))
{
return false;
}
// Checks if it is a mobile browser
string pattern = "up.browser|up.link|windows ce|iphone|iemobile|mini|mmp|symbian|midp|wap|phone|pocket|mobile|pda|psp";
MatchCollection mc = Regex.Matches(user_agent, pattern, RegexOptions.IgnoreCase);
if (mc.Count > 0)
return true;
// Checks if the 4 first chars of the user-agent match any of the most popular user-agents
string popUA = "|acs-|alav|alca|amoi|audi|aste|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg-c|lg-d|lg-g|lge-|maui|maxo|midp|mits|mmef|mobi|mot-|moto|mwbp|nec-|newt|noki|opwv|palm|pana|pant|pdxg|phil|play|pluc|port|prox|qtek|qwap|sage|sams|sany|sch-|sec-|send|seri|sgh-|shar|sie-|siem|smal|smar|sony|sph-|symb|t-mo|teli|tim-|tosh|tsm-|upg1|upsi|vk-v|voda|w3c |wap-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda-|";
if (popUA.Contains("|" + user_agent.Substring(0, 4) + "|"))
return true;
}
// Checks the accept header for wap.wml or wap.xhtml support
string accept = curcontext.Request.ServerVariables["HTTP_ACCEPT"];
if (accept != null )
{
if (accept.Contains("text/vnd.wap.wml") || accept.Contains("application/vnd.wap.xhtml+xml"))
{
return true;
}
}
// Checks if it has any mobile HTTP headers
string x_wap_profile = curcontext.Request.ServerVariables["HTTP_X_WAP_PROFILE"];
string profile = curcontext.Request.ServerVariables["HTTP_PROFILE"];
string opera = curcontext.Request.Headers["HTTP_X_OPERAMINI_PHONE_UA"];
if (x_wap_profile != null || profile != null || opera != null )
{
return true;
}
return false;
}