开发者

Allow user when registered to browse to username.host.com

开发者 https://www.devze.com 2023-04-05 02:11 出处:网络
I am using Asp.net MVC3 and C# and IIS 7.5. I want that once user is registered he can browse my site using username.host.com and this username should be available to me in my query string so I can sh

I am using Asp.net MVC3 and C# and IIS 7.5. I want that once user is registered he can browse my site using username.host.com and this username should be available to me in my query string so I can show the data related to that particular username only. All the logic is the same for all users. I don't want to do any fancy thing like开发者_运维问答 if user1.host.com is entered then I want to redirect to a separate controller and action etc. All the application logic is the same for all users. I just want to change the way the url is shown in the browser.

Note: I am not talking about really creating dynamic subdomains. That is a lot of task!

Because routing is so powerful in MVC, I assume that it can be done alone using routing. Also, if possible I want this to work on localhost also in IIS/Cassini.

Eg: If I browse to jaggu.localhost:19883. It should send me to localhost:19883/Home/index/Jaggu (because by default Home is the controller and index is the method)

I am completely clueless on how to achieve this. Any help would be appreciated.

Thanks.


In terms of ASP.NET MVC routing it's easy. Simply write a custom route:

public class MyRoute : Route
{
    public MyRoute(string url, object defaults)
        : base(url, new RouteValueDictionary(defaults), new MvcRouteHandler())
    { }

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var rd = base.GetRouteData(httpContext);
        var tokens = httpContext.Request.Url.Host.Split('.');
        if (tokens.Length > 1)
        {
            rd.Values["username"] = tokens[0];
        }
        return rd;
    }
}

and then register this route:

routes.Add(
    "Default",
    new MyRoute(
        "{controller}/{action}/{username}",
        new { controller = "Home", action = "Index", username = UrlParameter.Optional }
    )
);

Now when someone requests http://foo.host.com, automatically the Index action of the HomeController will be invoked and passed username="foo" parameter.

Then comes the difficult part. The registration and management of subdomains and web server configuration. A topic better suited to be discussed on http://serverfault.com


It is significantly easier to work with www.{site}.com/{username} than what you are trying to do.

subdomains are meant to section off separate websites; not content areas.

Even if you get it to work, you will discover more issues like dealing with SSL certs (if you need them) and the browser's always fun "same origin policy."

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号