如何在ASP.NET Core 2.2中构建导航菜单

时间:2019-07-16 17:04:39

标签: c# asp.net-core asp.net-core-2.0

我正在编写一个库,该库可以帮助向Asp.Net Core网站添加导航菜单,因为MvcSiteMapProvider不支持asp.net Core。

我写了一个提供程序,可以解析xml并创建html标记。 但是我不知道如何在目标Web客户端中使用库的最佳实践。

现在的样子: 1.为启动添加了服务:

services.AddHttpContextAccessor();
services.AddTransient<ICustomSitemapProvider, CustomSitemapProvider>();
  1. 在_Layout.cshtml
@inject Microsoft.AspNetCore.Http.IHttpContextAccessor HttpContextAccessor

及以下:

<div class="page-sidebar navbar-collapse collapse">
@Html.RenderNavigation(HttpContextAccessor)
</div>

这里是扩展名,用于_Layout。

public static class SitemapHelper
    {
        public static IHtmlContent RenderNavigation(this IHtmlHelper helper, IHttpContextAccessor httpContextAccessor)
        {
            var smp = new CustomSitemapProvider();

            var sitemap = smp.RenderNavigation();

            var sb = new StringBuilder();

            var rootNode = sitemap.Nodes.FirstOrDefault(x => x.IsRoot);

            MarkNodesAsSelected(sitemap.Nodes, rootNode, httpContextAccessor.HttpContext.Request.Path);

            sb.Append("<ul class='page-sidebar-menu  page-header-fixed' data-keep-expanded='false' data-auto-scroll='true' data-slide-speed='200'>");

            foreach (var item in sitemap.Nodes)
            {
                Build(item, rootNode, sb, httpContextAccessor.HttpContext.Request.Path);
            }

            sb.Append("</ul>");

            return helper.Raw(sb.ToString());
        }
}

 public class CustomSitemapProvider : ICustomSitemapProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CustomSitemapProvider(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public SitemapRoot RenderNavigation()
        {
            //1. Parse sitemap
            var sitemap = ParseXmlSitemap();

            return sitemap;
        }

        private SitemapRoot ParseXmlSitemap()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(SitemapRoot));

            var input = File.OpenText(@"map.xml").ReadToEnd();

            using (var xmlReader = new XmlTextReader(new StringReader(input)))
            {
               var output = (SitemapRoot)serializer.Deserialize(xmlReader);

                return output;
            }
        }

它可以工作,但是主要问题是性能。 现在,我的库读取并解析xml映射,在每次单击导航项时建立html标记。 还有什么,如果我想添加一些选项(如启用/禁用区域,启用禁用权限过滤器(以将某些导航项限制为用户,这些用户无权查看该页面)等)。 从视图发送这些选项不是一个好主意。

0 个答案:

没有答案