C#如何配置动态路由,从数据库读取html代码直达前端访问模板页面

2024-03-30 10:00:14

一、我们在开发模板网站时,需要配置动态路由,就是根据我们事先设定的控制器名称和视图名称,用户可以直接访问该地址,不需要手工一个一个页面生成才可以进行访问。



public static void RegisterRoutes(RouteCollection routes)

{

routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.Add("Urldemolist", new DomainRoute(

"{CityUrl}.abc.com",

"{controller}/{action}.html",

new { CityUrl = "www", controller = "Channel", action = "Channel", id = UrlParameter.Optional }

));

//首页

routes.Add("Index1", new DomainRoute(

"{CityUrl}.abc.com",

"",

new { CityUrl = "www", controller = "Home", action = "Index", id = UrlParameter.Optional }

));

routes.MapRoute(

name: "Default",

url: "{controller}/{action}.html",

defaults: new { controller = "Channel", action = "Channel", id = UrlParameter.Optional }

);

routes.MapRoute(

name: "Default2",

url: "{controller}/{action}",

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

);

}

二、从数据库读取html代码直达前端访问模板页面



WisdomStarsEntities ef = new WisdomStarsEntities();

CMSCommons obj1 = new CMSCommons();

#region 首页或频道页

public ActionResult Index(string dynamicRoute)

{

//string viewFile = "/Views/" + dynamicRoute + ".cshtml";

//return Content(viewFile);

//return View(viewFile);

// 1:首页 2:频道页 3:列表页 4:详细页 5:栏目页

int templateType = 1;

//获取子域名的字符串

string sortname = Request.RequestContext.RouteData.Values["CityUrl"].ToString();

var controllerName = RouteData.Route.GetRouteData(this.HttpContext).Values["controller"];

var actionName = RouteData.Route.GetRouteData(this.HttpContext).Values["action"];

decimal GetKindergartenID = obj1.GetKindergartenID(sortname);

//根据频道类型获取模板内容

//模板英文

string WT_en_Name = controllerName.ToString();

//频道目录

string catalogue = actionName.ToString();

//替换标签

string content1 = obj1.GetModel(WT_en_Name, catalogue, templateType, GetKindergartenID);

return Content(content1);

}

#endregion

三、获取子域名并重定向到指定的目录文件



WisdomStarsEntities ef = new WisdomStarsEntities();

public ActionResult Index()

{

string sortname = Request.RequestContext.RouteData.Values["CityUrl"].ToString();

hx_Kindergarten kindergartenmodel = ef.hx_Kindergarten.Where(a => a.domain == sortname).AsNoTracking().FirstOrDefault();

if (kindergartenmodel != null)

{

if (kindergartenmodel.WebTemplateID > 0)

{

HX_WB_WebTemplate templatemodel = ef.HX_WB_WebTemplate.Where(a => a.WebTemplateID == kindergartenmodel.WebTemplateID).AsNoTracking().FirstOrDefault();

if (templatemodel != null)

{

Response.Redirect("/" + templatemodel.WT_en_Name + "/index.html");

}

}

}

Response.Redirect("http://www.abc.com");

return View();

}

至此,C#如何配置动态路由,从数据库读取html代码直达前端访问模板页面方法已经介绍完毕,小伙伴是否能对你有所帮助呢?敬请留言!