Sobes.tech
Middle

How to implement user redirection from mobile devices to a mobile subdomain (like VKontakte)?

sobes.tech AI

Answer from AI

To redirect users from mobile devices to a mobile subdomain in C#, you can check the User-Agent in the HTTP request and perform a redirect to the desired subdomain. This is usually implemented in middleware or in the request handler.

Example in ASP.NET Core:

public class MobileRedirectMiddleware
{
    private readonly RequestDelegate _next;

    public MobileRedirectMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        var userAgent = context.Request.Headers["User-Agent"].ToString().ToLower();
        var host = context.Request.Host.Host;

        bool isMobile = userAgent.Contains("iphone") || userAgent.Contains("android") || userAgent.Contains("mobile");

        if (isMobile && !host.StartsWith("m."))
        {
            var newHost = "m." + host;
            var newUrl = $"{context.Request.Scheme}://{newHost}{context.Request.Path}{context.Request.QueryString}";
            context.Response.Redirect(newUrl, permanent: false);
            return;
        }

        await _next(context);
    }
}

// In Startup.cs, in the Configure method:
// app.UseMiddleware<MobileRedirectMiddleware>();

This approach allows automatic redirection of mobile users to the subdomain m.example.com, similar to what is done in VKontakte. It is important to note that User-Agent may not always be reliable, so specialized libraries can be used to detect devices.