首页 > 解决方案 > 如何在 Asp.NET Core 中呈现不同的布局

问题描述

我想在我的 asp.net 核心应用程序的某些页面上呈现空布局。为此,我在_ViewStart.cshtml.

@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    string cLayout = "";
    if (controller == "Empty")
    {
        cLayout = "~/Views/Shared/_Empty_Layout.cshtml";
    }
    else
    {
        cLayout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = cLayout;
}

此代码工作正常,Asp.NET MVC App但它在.NET Core App. 错误是The name 'HttpContext' does not exist in the current context

标签: c#asp.net-core

解决方案


HttpContext.Current这是微软的一个非常糟糕的想法,幸运的是,它没有迁移到 ASP.NET Core。

您可以RouteData像这样访问:

@Url.ActionContext.RouteData.Values["Controller"]
// or
@ViewContext.RouteData.Values["Controller"]

也就是说,“空布局”听起来你根本不想要布局。如果是这种情况,请使用:

@{
    var controller = ViewContext.RouteData.Values["Controller"].ToString();
    string layout = null;
    if (controller != "Empty")
    {
        layout = "~/Views/Shared/_Layout.cshtml";
    }
    Layout = layout;
}

null这里的意思是“不要使用布局”。


推荐阅读