【问题标题】:Including static html file from ~/Content into ASP.NET MVC view将 ~/Content 中的静态 html 文件包含到 ASP.NET MVC 视图中
【发布时间】:2011-07-29 22:30:59
【问题描述】:

我的项目中有母版页,其中包含一些关于网站版权的信息和一些联系信息。我想把它从母版页中取出并放在一个静态文件中(出于某种原因,这些文件必须放在 ~/Content 文件夹中)。有没有一种方法可以让我在我看来像

<% Html.Include("~/Content/snippet.html") %>   // not a real code

?

【问题讨论】:

    标签: html asp.net-mvc view


    【解决方案1】:

    对于 ASP .NET Core 3.1 Razor 页面,您可以这样做:

    @Html.Raw(System.IO.File.ReadAllText("wwwroot/Content/snippet.html"));
    

    在此处查看有关静态文件的文档:

    https://docs.microsoft.com/en-us/aspnet/core/fundamentals/static-files?view=aspnetcore-3.1

    【讨论】:

      【解决方案2】:

      使用您自己的视图引擎

      使用

      @Html.Partial("_CommonHtmlHead")
      

      作为

      /Views/Shared/_CommonHtmlHead.html
      

      /Views/MyArea/Shared/_CommonHtmlHead.htm
      

      对我来说是最好的。

      使用 System.Web.Mvc.VirtualPathProviderViewEngine 升序类为此创建自己的视图引擎似乎相对容易:

      /// <summary>
      /// Simple render engine to load static HTML files, supposing that view files has the html/htm extension, supporting replacing tilda paths (~/MyRelativePath) in the content
      /// </summary>
      public class HtmlStaticViewEngine : VirtualPathProviderViewEngine
      {
          private static readonly ILog _log = LogManager.GetLogger(typeof (HtmlStaticViewEngine));
      
          protected readonly DateTime? AbsoluteTimeout;
          protected readonly TimeSpan? SlidingTimeout;
          protected readonly CacheItemPriority? Priority;
      
          private readonly bool _useCache;
      
          public HtmlStaticViewEngine(TimeSpan? slidingTimeout = null, DateTime? absoluteTimeout = null, CacheItemPriority? priority = null)
          {
              _useCache = absoluteTimeout.HasValue || slidingTimeout.HasValue || priority.HasValue;
      
              SlidingTimeout = slidingTimeout;
              AbsoluteTimeout = absoluteTimeout;
              Priority = priority;
      
              AreaViewLocationFormats = new[]
              {
                  "~/Areas/{2}/Views/{1}/{0}.html",
                  "~/Areas/{2}/Views/{1}/{0}.htm",
                  "~/Areas/{2}/Views/Shared/{0}.html",
                  "~/Areas/{2}/Views/Shared/{0}.htm"
              };
              AreaMasterLocationFormats = new[]
              {
                  "~/Areas/{2}/Views/{1}/{0}.html",
                  "~/Areas/{2}/Views/{1}/{0}.htm",
                  "~/Areas/{2}/Views/Shared/{0}.html",
                  "~/Areas/{2}/Views/Shared/{0}.htm"
              };
              AreaPartialViewLocationFormats = new[]
              {
                  "~/Areas/{2}/Views/{1}/{0}.html",
                  "~/Areas/{2}/Views/{1}/{0}.htm",
                  "~/Areas/{2}/Views/Shared/{0}.html",
                  "~/Areas/{2}/Views/Shared/{0}.htm"
              };
      
              ViewLocationFormats = new[]
              {
                  "~/Views/{1}/{0}.html",
                  "~/Views/{1}/{0}.htm",
                  "~/Views/Shared/{0}.html",
                  "~/Views/Shared/{0}.htm"
              };
              MasterLocationFormats = new[]
              {
                  "~/Views/{1}/{0}.html",
                  "~/Views/{1}/{0}.htm",
                  "~/Views/Shared/{0}.html",
                  "~/Views/Shared/{0}.htm"
              };
              PartialViewLocationFormats = new[]
              {
                  "~/Views/{1}/{0}.html",
                  "~/Views/{1}/{0}.htm",
                  "~/Views/Shared/{0}.html",
                  "~/Views/Shared/{0}.htm"
              };
      
              FileExtensions = new[]
              {
                  "html",
                  "htm",
              };
          }
      
          protected virtual string GetContent(string viewFilePath)
          {
              string result = null;
              if (!string.IsNullOrWhiteSpace(viewFilePath))
              {
                  if (_useCache)
                  {
                      result = TryCache(viewFilePath);
                  }
      
                  if (result == null)
                  {
                      using (StreamReader streamReader = File.OpenText(viewFilePath))
                      {
                          result = streamReader.ReadToEnd();
                      }
      
                      result = ParseContent(result);
      
                      if (_useCache)
                      {
                          CacheIt(viewFilePath, result);
                      }
                  }
              }
      
              return result;
          }
      
          static readonly Regex TildaRegularExpression = new Regex(@"~/", RegexOptions.Compiled);
      
          /// <summary>
          /// Finds all tilda paths in the content and replace it for current path
          /// </summary>
          /// <param name="content"></param>
          /// <returns></returns>
          protected virtual string ParseContent(string content)
          {
              if (String.IsNullOrWhiteSpace(content))
              {
                  return content;
              }
      
              string absolutePath = VirtualPathUtility.ToAbsolute("~/");
      
              string result = TildaRegularExpression.Replace(content, absolutePath);
              return result;
          }
      
          protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
          {
              HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
      
              string filePath = httpContextBase.Server.MapPath(partialPath);
              string content = GetContent(filePath);
              return new StaticView(content);
          }
      
          protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
          {
              HttpContextBase httpContextBase = controllerContext.RequestContext.HttpContext;
              
              string result = null;
              if (!string.IsNullOrWhiteSpace(masterPath))
              {
                  string filePath = httpContextBase.Server.MapPath(masterPath);
                  result = GetContent(filePath);
              }
      
              string physicalViewPath = httpContextBase.Server.MapPath(viewPath);
              result += GetContent(physicalViewPath);
              return new StaticView(result);
          }
      
          protected virtual string TryCache(string filePath)
          {
              HttpContext httpContext = HttpContext.Current;
              if (httpContext != null && httpContext.Cache != null)
              {
                  string cacheKey = CacheKey(filePath);
                  return (string)httpContext.Cache[cacheKey];
              }
              return null;
          }
      
          protected virtual bool CacheIt(string filePath, string content)
          {
              HttpContext httpContext = HttpContext.Current;
              if (httpContext != null && httpContext.Cache != null)
              {
                  string cacheKey = CacheKey(filePath);
                  httpContext.Cache.Add(cacheKey, content, new CacheDependency(filePath), AbsoluteTimeout.GetValueOrDefault(Cache.NoAbsoluteExpiration), SlidingTimeout.GetValueOrDefault(Cache.NoSlidingExpiration), Priority.GetValueOrDefault(CacheItemPriority.AboveNormal), CacheItemRemovedCallback);
                  return true;
              }
      
              return false;
          }
      
          protected virtual string CacheKey(string serverPath)
          {
              return serverPath;
          }
      
          protected virtual void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
          {
              _log.InfoFormat("CacheItemRemovedCallback(string key='{0}', object value = ..., {1} reason={2})", key, reason.GetType().Name, reason);
          }
      }
      
      public class MvcApplication : System.Web.HttpApplication
      {
          protected void Application_Start()
          {
              ViewEngines.Engines.Add(new HtmlStaticViewEngine(new TimeSpan(12,0,0,0)));
          }
      }
      
      public class StaticView : IView
      {
          private readonly string _text;
      
          public StaticView(string text)
          {
              _text = text;
          }
      
          public void Render(ViewContext viewContext, TextWriter writer)
          {
              if (! string.IsNullOrEmpty(_text))
              {
                  writer.Write(_text);
              }
          }
      }
      

      注意: 此代码仅通过简单的渲染用法进行测试 部分视图

      【讨论】:

        【解决方案3】:

        最好使用局部视图(即使它只包含静态文本)并将其包含在 Html.Partial 帮助器中。但如果你坚持:

        <%= File.ReadAllText(Server.MapPath("~/Content/snippet.html")) %>
        

        【讨论】:

        • 将 sn-ps 存储在 Content 文件夹中是有特殊原因的。我们有同一个应用程序的多个实例,每个实例都可以访问存储在一个地方的相同 dll。要自定义每个实例,我们只能更改 Content 文件夹中的项目。
        • 您的回答似乎正是我所需要的。谢谢!
        • 你的答案是 Grate,除了 File 需要放置 IO.File :)
        【解决方案4】:

        如果您在 .Net MVC 5 中并希望将 HTML 文件包含在部分文件中,而不需要 Razor 来呈现它:

        @Html.Raw(File.ReadAllText(Server.MapPath("~/Views/Shared/ICanHaz.html")))
        

        【讨论】:

          【解决方案5】:

          要将静态 html 文件包含到 MVC 视图中,如下所示:

          <!-- #include virtual="~\Content\snippet.htm" -->
          

          【讨论】:

            【解决方案6】:

            您将内容保存在 HTML 文件中而不是部分视图中是否有原因?

            如果您在Views/Shared 文件夹中创建一个名为snippet.ascx 的文件,您可以使用&lt;% Html.RenderPartial("snippet"); %&gt; 将该snippet.ascx 文件的内容导入到任何视图中

            【讨论】:

            • 是的,这是有原因的。
            • 就像与没有 Visual Studio 的人一起工作 :-) 这对于将 vanilla html 快速集成到 MVC 解决方案中非常有用。
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-04-26
            • 2012-08-04
            • 2012-01-24
            相关资源
            最近更新 更多