我在_Layout.cshtml中有以下代码

 @Styles.Render("~/Content/css")

    @functions{
        public static string GetRootPath()
        {
            return string.Format("{0}", HttpRuntime.AppDomainAppVirtualPath == "/" ? "" : HttpRuntime.AppDomainAppVirtualPath);
        }
    }

<script type="text/javascript">
    var rootPath = '@Html.Raw(GetRootPath())';

</script>


我需要在.net core 2.1中实现相同的功能。我知道它与IHostingEnvironment有关,但是在我所知道的所有示例中,他们都将其注入到控制器或“启动”页面的功能中。如何在.net core 2.1的_Layout.cshtml中实现以上功能?

最佳答案

要访问IHostingEnvironment中的View,可以尝试如下操作:

@using Microsoft.AspNetCore.Http;
@using Microsoft.AspNetCore.Hosting;
@inject IHttpContextAccessor HttpContextAccessor;
@inject IHostingEnvironment HostingEnvironment;
@{
    ViewData["Title"] = "About";
}
@HttpContextAccessor.HttpContext.Request.PathBase.Value;
@HostingEnvironment.WebRootPath;
@HostingEnvironment.ContentRootPath;

08-19 08:06