ASP.NET MVC的子域 [英] ASP.NET MVC Subdomains

查看:245
本文介绍了ASP.NET MVC的子域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经主机和域名一样,

I have hosting and domain like that:

www.EXAMPLE.com

我已经创建了几个子域这样的:

I've created few subdomains like that:

www.PAGE1.EXAMPLE.com
www.PAGE2.EXAMPLE.com
www.PAGE3.EXAMPLE.com
... etc...

所有这些子域名指向同一个ASP.NET MVC 5应用。

All of these subdomains point to one and the same ASP.NET MVC 5 Application.

我要让系统将加载取决于子域的数据。
例如:

I want to make system which will load data depending of subdomain. Example:

我有文章对象可以是一个自动回放或游戏审查或书评等...

I have Article object which could be a Auto Review or Game review or Book Review etc...

我想www.auto.example.com负载数据,其中文章类型为自动,以www.book.example.com我想装入类型的书等。

I would like to www.auto.example.com load data where type of article is Auto, to www.book.example.com I would like to load data with type Book etc.

将有许多类型的网页。

什么是做的最好的做法?

What is best practise to do that?

顶级域www.example.com应显示别的东西。这将是主要的页面为其他。

The top level domain www.example.com should display something else. It would be main page for the others.

推荐答案

您可以通过编写自定义路由做到这一点。下面是如何(摘自<一个href=\"http://stackoverflow.com/questions/278668/is-it-possible-to-make-an-asp-net-mvc-route-based-on-a-subdomain\">Is有可能使基于子域的ASP.NET MVC路线?)

You can do this by writing a custom Route. Here's how (adapted from Is it possible to make an ASP.NET MVC route based on a subdomain?)

public class SubdomainRoute : RouteBase
{

    public override RouteData GetRouteData(HttpContextBase httpContext)
    {
        var host = httpContext.Request.Url.Host;
        var index = host.IndexOf(".");
        string[] segments = httpContext.Request.Url.PathAndQuery.Split('/');

        if (index < 0)
            return null;

        var subdomain = host.Substring(0, index);
        string controller = (segments.Length > 0) ? segments[0] : "Home";
        string action = (segments.Length > 1) ? segments[1] : "Index";

        var routeData = new RouteData(this, new MvcRouteHandler());
        routeData.Values.Add("controller", controller); //Goes to the relevant Controller  class
        routeData.Values.Add("action", action); //Goes to the relevant action method on the specified Controller
        routeData.Values.Add("subdomain", subdomain); //pass subdomain as argument to action method
        return routeData;
    }

    public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
        //Implement your formating Url formating here
        return null;
    }
}

添加到路由表中的Global.asax.cs是这样的:

Add to the route table in Global.asax.cs like this:

routes.Add(new SubdomainRoute());

和您的控制器的方法:

public ActionResult Index(string subdomain)
{
    //Query your database for the relevant articles based on subdomain
    var viewmodel = MyRepository.GetArticles(subdomain);
    Return View(viewmodel);
}

这篇关于ASP.NET MVC的子域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆