gpt4 book ai didi

asp.net-mvc - ASP.NET MVC 子域

转载 作者:行者123 更新时间:2023-12-04 02:55:43 24 4
gpt4 key购买 nike

我有这样的托管和域名:

www.EXAMPLE.com

我创建了几个这样的子域:
www.PAGE1.EXAMPLE.com
www.PAGE2.EXAMPLE.com
www.PAGE3.EXAMPLE.com
... etc...

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

我想制作一个可以根据子域加载数据的系统。
例子:

我有文章对象,可以是自动评论或游戏评论或书评等...

我想在 www.auto.example.com 加载文章类型为 Auto 的数据,到 www.book.example.com 我想加载 Book 等类型的数据。

将有许多类型的页面。

这样做的最佳做法是什么?

顶级域 www.example.com 应该显示其他内容。这将是其他人的主页。

最佳答案

您可以通过编写自定义路由来做到这一点。方法如下(改编自 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 中的路由表,如下所示:
routes.Add(new SubdomainRoute());

和你的 Controller 方法:
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 - ASP.NET MVC 子域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20609776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com