小編典典
您可以使用限制來決定是否覆寫預設路由邏輯。
public class CmsUrlConstraint : IRouteConstraint
{
public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
{
var db = new MvcCMS.Models.MvcCMSContext();
if (values[parameterName] != null)
{
var permalink = values[parameterName].ToString();
return db.CMSPages.Any(p => p.Permalink == permalink);
}
return false;
}
}
在路由定義中使用它,例如
routes.MapRoute(
name: "CmsRoute",
url: "{*permalink}",
defaults: new {controller = "Page", action = "Index"},
constraints: new { permalink = new CmsUrlConstraint() }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
現在,如果您在“頁面”控制器中執行“索引”操作,
public ActionResult Index(string permalink)
{
//load the content from db with permalink
//show the content with view
}
所有網址将被第一個路由捕獲,并由限制條件進行驗證。
如果永久連結存在于db中,則URL将由Page控制器中的Index操作處理。
如果不是這樣,限制将失敗并且URL将回退到預設路由(我不知道您在項目中是否還有其他控制器以及如何決定404邏輯)。
編輯
為了避免Index在Page控制器的操作中重新查詢cms頁面,可以使用HttpContext.Items字典,例如
在限制中
var db = new MvcCMS.Models.MvcCMSContext();
if (values[parameterName] != null)
{
var permalink = values[parameterName].ToString();
var page = db.CMSPages.Where(p => p.Permalink == permalink).FirstOrDefault();
if(page != null)
{
HttpContext.Items["cmspage"] = page;
return true;
}
return false;
}
return false;
然後在行動中
public ActionResult Index(string permalink)
{
var page = HttpContext.Items["cmspage"] as CMSPage;
//show the content with view
}
希望這可以幫助。
2020-05-19