将 ~/Content 中的静态 html 文件包含到 ASP.NET MVC 视图中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5551814/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:47:53  来源:igfitidea点击:

Including static html file from ~/Content into ASP.NET MVC view

htmlasp.net-mvcview

提问by HiveHicks

I've got master page in my project, which contains some information about site copyright and some contact info in it. I'd like to take it out of master page and place it in a static files (for some reason, these files must be placed in ~/Content folder). Is there a way that I can tell in my view something like

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

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

?

?

回答by Darin Dimitrov

You are better off using a partial view (even if it only contains static text) and include it with the Html.Partialhelper. But if you insist:

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

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

回答by Olivier de Rivoyre

If you are in .Net MVC 5 and want to include a HTML file a partial file without having Razor that render it:

如果您在 .Net MVC 5 中并且想要在没有 Razor 渲染它的情况下将 HTML 文件包含为部分文件:

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

回答by Motlicek Petr

Use your own view engine

使用你自己的视图引擎

using

使用

@Html.Partial("_CommonHtmlHead")

as

作为

/Views/Shared/_CommonHtmlHead.html

or

或者

/Views/MyArea/Shared/_CommonHtmlHead.htm

is the best for me.

对我来说是最好的。

Creating your own view engine for this by using the System.Web.Mvc.VirtualPathProviderViewEngine ascending class seems to be relatively easy:

使用 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);
        }
    }
}

NOTE: This code is tested only with simple usage for rendering partial views

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

回答by AndyM

Is there a reason you are holding the content in an HTML file rather than a partial view?

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

If you create a file called snippet.ascxin your Views/Sharedfolder you can import the content of that snippet.ascxfile into any view by using <% Html.RenderPartial("snippet"); %>

如果您snippet.ascxViews/Shared文件夹中创建一个名为的文件,您可以snippet.ascx使用以下命令将该文件的内容导入到任何视图中<% Html.RenderPartial("snippet"); %>

回答by T Gupta

To include static html file into a MVC View goes like this:

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

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