【问题标题】:How do you include .html or .asp file using razor?如何使用 razor 包含 .html 或 .asp 文件?
【发布时间】:2011-03-15 16:02:30
【问题描述】:

是否可以在 Razor 视图引擎中使用服务器端包含来包含 .html 或 .asp 文件?我们有一个 .html 文件和 .asp 文件,其中包含用于我们所有网站的网站菜单。目前我们对所有网站都使用服务器端包含,因此我们只需要在一个地方更改菜单。

我的 _Layout.cshtml 正文中有以下代码

<body>
<!--#include virtual="/serverside/menus/MainMenu.asp" -->   
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->
@RenderBody()
</body>

如果我查看源代码,我会看到文字文本,而不是包含文件的内容。

" <!--#include virtual="/serverside/menus/MainMenu.asp" --> 
    <!--#include virtual="/serverside/menus/library_menu.asp" -->
    <!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->"

【问题讨论】:

    标签: asp.net-mvc-3 razor


    【解决方案1】:
    @Html.Raw(File.ReadAllText(Server.MapPath("~/content/somefile.css")))
    

    【讨论】:

    • @AndrewBarber - 你能详细说明一下吗?我知道它不适用于 .asp 文件,因为不会加载渲染引擎,但它适用于 .html(和其他静态文件),对吧?
    • 是的,这适用于作为问题一部分的静态文件。我遇到了需要在我的页面中包含 .svg 文件的问题,这是最简单的解决方案
    • 我知道这个问题很老,但你的答案正是我想要在我的页面上包含一个 SVG 文件作为 HTML 的答案!干得好!
    【解决方案2】:

    尝试将您的 html 页面制作为 cshtml 页面并将其包含在:

    @RenderPage("_header.cshtml")
    

    【讨论】:

    • 此方法适用于包含静态页面。使用相对 url 作为 cshtml 页面的路径。
    • 这仅适用于包含 cshtml 页面而不是直接 html 页面的情况。
    • cshtml页面将被缓存。您还可以将缓存配置为非常激进(使用[OutputCache] 属性和较长的生命周期)。
    • 执行此操作时出现此错误Failed to load resource: the server responded with a status of 403 (Forbidden)
    【解决方案3】:

    尝试实现这个 HTML 助手:

    public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
    {
        var filePath = HttpContext.Current.Server.MapPath(serverPath);
    
        // load from file
        using (var streamReader = File.OpenText(filePath))
        {
            var markup = streamReader.ReadToEnd();
            return new HtmlString(markup);
        }
    }
    

    或:

    public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
    {
        var filePath = HttpContext.Current.Server.MapPath(serverPath);
    
        var markup = File.ReadAllText(filePath);
        return new HtmlString(markup);
    }
    

    【讨论】:

      【解决方案4】:
      @RenderPage("PageHeader.cshtml")
      <!-- your page body here -->
      @RenderPage("PageFooter.cshtml")
      

      这很好用,可以为您节省大量时间。

      【讨论】:

      • 这对我有用。唯一需要注意的是,您不能使用将参数(模型对象)传递给子页面的 RenderPage() 重载。子页面必须使用与父页面相同的模型对象。
      • 执行此操作时出现此错误Failed to load resource: the server responded with a status of 403 (Forbidden)
      【解决方案5】:

      Razor 不支持服务器端包含。最简单的解决方案是将菜单标记复制到您的 _Layout.cshtml 页面中。

      如果您只需要包含 .html 文件,您可能会编写一个自定义函数,从磁盘读取文件并写入输出。

      但是,由于您还想包含 .asp 文件(可能包含任意服务器端代码),上述方法将不起作用。您必须有一种方法来执行 .asp 文件、捕获生成的输出并将其写入您的 cshtml 文件中的响应。

      在这种情况下,我会采用复制+粘贴的方法

      【讨论】:

      • Server.Execute - 性能不佳,但我猜他很绝望,因为他正试图将经典 asp 与剃须刀一起使用。
      【解决方案6】:

      创建一个获取文件内容的 HtmlHelper 扩展方法:

      public static class HtmlHelpers
      {
        public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string url)
        {
          return MvcHtmlString.Create(new WebClient().DownloadString(url));
        }
      }
      

      用法:

      @Html.WebPage("/serverside/menus/MainMenu.asp");
      

      【讨论】:

      • 与老式服务器端包含的性能相比如何?
      • 我对服务器端包含的机制知之甚少。如果渲染引擎足够聪明,可以以某种方式异步下载和注入包含资源的内容,它可能会稍微快一些。但我认为获取资源的实际延迟会更大。
      • 另一种可能性是使用一些 JQuery 创建 HtmlHelper 或部分 Razor 视图,或者直接将 JQuery 放在母版页中,让 JQuery 下载并异步更新 div。但如果我不幸不得不这样做,我可能会坚持我原来的答案,但添加异常处理并将结果缓存在字典中,使用 url 作为键。
      • 您可能想要执行 Server.MapPath(url) 以获取完整路径名,然后使用 File.ReadAllText 加载文件 - 而不是使用 WebClient
      • 这会比创建csthml页面慢很多
      【解决方案7】:

      抱歉,伙计们的回答有点老了,但我找到了一些用剃刀附加 asp 文件的方法。当然,您需要做一些技巧,但它有效!首先,我创建了 .NET MVC 3 应用程序。

      在我的 _Layout.cshtml 中,我添加了以下行:

      @Html.Partial("InsertHelper")
      

      然后我在我的共享文件夹中创建了 InsertHelper.aspx,内容如下:

      <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
      
      <!--#include VIRTUAL="/ViewPage1.aspx"-->
      

      ViewPage1.aspx 位于我的根目录中,只需简单的 if 即可检查它是否有效:

      <%
      string dummy;
      dummy="nz";
      %>
      
      <% if (dummy == "nz") { %>
      nz indeed
      <% } else { %>
      not nz
      <% } %>
      

      而且它有效!

      Razor 能够使用不同的 ViewEngine 渲染局部,这就是这个示例有效的原因。

      还有一件事:记住不要在两个 aspx 文件中添加以下行:

      <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
      

      您只能添加一次!希望对您有所帮助!

      【讨论】:

        【解决方案8】:

        当我尝试在 MVC 4 中包含 .inc 文件时遇到了同样的问题。

        为了解决这个问题,我将文件的后缀更改为.cshtml,并添加了以下行

        @RenderPage("../../Includes/global-banner_v4.cshtml")
        

        【讨论】:

        • 执行此操作时出现此错误Failed to load resource: the server responded with a status of 403 (Forbidden)
        【解决方案9】:

        只要做:

        @Html.Partial("_SliderPartial")
        

        虽然“_SliderPartial”是你的“_SliderPartial.cshtml”文件,但你没问题。

        【讨论】:

          【解决方案10】:

          在我的 _Layout.cshtml 中,我添加了以下行:

          @Html.Partial("InsertHelper")
          

          然后我在我的共享文件夹中创建了 InsertHelper.aspx,内容如下:

          <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
          
          <!--#include VIRTUAL="/ViewPage1.aspx"-->
          

          【讨论】:

          • 而不是说它对您有用,而是为正确的解决方案投票并添加评论。
          【解决方案11】:

          为什么不在您的 _Layout.cshtml 页面中包含一个部分,该部分将允许您根据要使用的菜单呈现部分。

          _Layout.cshtml

          <!-- Some stuff. -->
          @RenderSection("BannerContent")
          <!-- Some other stuff -->
          

          然后,在任何使用该布局的页面中,您都会有这样的内容:

          @section BannerContent 
          {
            @*Place your ASP.NET and HTML within this section to create/render your menus.*@
          }
          

          【讨论】:

            【解决方案12】:

            Html.Include(relativeVirtualPath) 扩展方法

            出于文档目的,我想包含这样的文件(将文件的内容放在

             标记中)。
            
            

            为此,我添加了一个 HtmlHelperExtension 方法,该方法采用相对虚拟路径(不必是绝对虚拟路径)和一个可选的布尔值来指示您是否希望对内容进行 html 编码,默认情况下我方法确实如此,因为我主要使用它来显示代码。

            让这段代码工作的真正关键是使用VirtualPathUtilityWebPageBase。示例:

            // Assume we are dealing with Razor as WebPageBase is the base page for razor.
            // Making this assumption we can get the virtual path of the view currently
            // executing (will return partial view virtual path or primary view virtual
            // path just depending on what is executing).
            var virtualDirectory = VirtualPathUtility.GetDirectory(
               ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
            

            完整的 HtmlHelper 扩展代码:

            public static class HtmlHelperExtensions
            {
                private static readonly IEnumerable<string> IncludeFileSupportedExtensions = new String[]
                {
                    ".resource",
                    ".cshtml",
                    ".vbhtml",
                };
            
                public static IHtmlString IncludeFile(
                   this HtmlHelper htmlHelper, 
                   string virtualFilePath, 
                   bool htmlEncode = true)
                {
                    var virtualDirectory = VirtualPathUtility.GetDirectory(
                        ((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
                    var fullVirtualPath = VirtualPathUtility.Combine(
                        virtualDirectory, virtualFilePath);
                    var filePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(
                        fullVirtualPath);
            
                    if (File.Exists(filePath))
                    {
                        return GetHtmlString(File.ReadAllText(filePath), htmlEncode);
                    }
                    foreach (var includeFileExtension in IncludeFileSupportedExtensions)
                    {
                        var filePathWithExtension = filePath + includeFileExtension;
                        if (File.Exists(filePathWithExtension))
                        {
                            return GetHtmlString(File.ReadAllText(filePathWithExtension), htmlEncode);
                        }
                    }
                    throw new ArgumentException(string.Format(
            @"Could not find path for ""{0}"".
            Virtual Directory: ""{1}""
            Full Virtual Path: ""{2}""
            File Path: ""{3}""",
                                virtualFilePath, virtualDirectory, fullVirtualPath, filePath));
                }
            
                private static IHtmlString GetHtmlString(string str, bool htmlEncode)
                {
                    return htmlEncode
                        ? new HtmlString(HttpUtility.HtmlEncode(str))
                        : new HtmlString(str);
                }
            }
            

            【讨论】:

              【解决方案13】:

              您可以在 .cshtml 文件中包含服务器端代码和 aspx 文件,如下所示,然后包含经典的 asp 文件或 html 文件。 以下是步骤

              1. Index.cshtml
              @Html.RenderPartial("InsertASPCodeHelper")

              2.插入ASPCodeHelper.aspx

              <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
              <!--#include VIRTUAL="~/Views/Shared/Header.aspx"-->
              
              1. Header.aspx
              <!--#include file="/header/header.inc"-->
              

              【讨论】:

                【解决方案14】:

                使用包含不是在 mvc 中使用菜单的正确方法。您应该使用共享布局和/或部分视图。

                但是,如果出于某种奇怪的原因,您必须包含一个 html 文件,这是一种方法。

                Helpers/HtmlHelperExtensions.cs

                using System.Web;
                using System.Web.Mvc;
                using System.Net;
                
                namespace MvcHtmlHelpers
                {
                    public static class HtmlHelperExtensions
                    {
                        public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string serverPath)
                        {
                            var filePath = HttpContext.Current.Server.MapPath(serverPath);
                            return MvcHtmlString.Create(new WebClient().DownloadString(filePath));
                        }
                    }
                }
                

                向 web.config 添加新的命名空间

                <pages pageBaseType="System.Web.Mvc.WebViewPage">
                  <namespaces>
                    <add namespace="MvcHtmlHelpers"/>
                  </namespaces>
                </pages>
                

                用法:

                @Html.WebPage("/Content/pages/home.html")
                

                【讨论】:

                  猜你喜欢
                  • 2010-10-01
                  • 1970-01-01
                  • 2012-04-08
                  • 1970-01-01
                  • 2012-04-23
                  • 1970-01-01
                  • 1970-01-01
                  • 2011-08-20
                  • 2018-05-09
                  相关资源
                  最近更新 更多