【问题标题】:update og/meta tags with angular in .net core在 .net 核心中使用 Angular 更新 og/meta 标签
【发布时间】:2018-03-28 20:58:01
【问题描述】:

我正在尝试添加 facebook 将拾取的 og 标签,从我在网上找到的内容来看,听起来 angular universal 现在已合并到 angular 中,并且应该能够通过使用平台浏览器库来做到这一点。

我开始了一个全新的 .net 核心项目,支持角度。它创建了 3 个角度组件,我希望我可以对其进行测试以尝试设置 og 标签 - counter.component.ts、fetchdata.component.ts 和 home.component.ts。下面是我在 counter.component.ts 构造函数中的示例。

constructor(private meta: Meta) {
    this.meta.addTags([
        { property: 'og:url', content: 'https://www.oursite.com/counter' },
        { property: 'og:title', content: 'Counter Page' },
        { property: 'og:description', content: 'Counter page description' },
        { property: 'og:image', content: 'https://www.oursite.com/images/angular/counter-page.png' }
    ], false);
}

当我运行它并查看源代码时,它实际上添加了 og 标记,但是它们在 app 标记内它自己的 html 结构中呈现。

<html>
  <body>
    <app>
      <html>
        <head>
          <meta property="og:title" content="Counter Page">

我为 boot.server.ts 文件找到了一些代码,它删除了只留下元数据的额外标签,但因为它们不在实际的头标签中,facebook 的调试器仍然无法识别它们。

resolve({
   html: state.renderToString()
       .replace('<html><head>', '')
       .replace('</head><body>', '')
       .replace(/<\s*app.*?>/, '')
       .replace('</app></body></html>', '')
});

我读过的所有内容都让人觉得它应该是这样工作的,而且它对 SEO/社交媒体很友好。但显然不是。我不确定这是它的预期工作方式还是 .net 核心模板设置不正确?

【问题讨论】:

    标签: angular asp.net-core-2.0


    【解决方案1】:

    我不认为这是准确的:“听起来 Angular 通用现在已合并到 Angular 中,并且应该能够通过使用平台浏览器库来做到这一点。”他们在 Angular 4 中添加了 MetaService,但这与将 Angular Universal 的服务器端渲染功能添加到 Angular 中不同。

    Facebook 和 Twitter 爬虫(与 Google 不同)不执行任何 JavaScript,因此您必须通过服务器端呈现来执行此操作。我通过切换到 Angular Universal 然后使用 MetaService 来做到这一点。

    请注意,移植到 Angular Universal 可能是一个重大变化,因此在决定是否要实现飞跃之前,请先进行研究。

    【讨论】:

      【解决方案2】:

      我尝试了一个我在我的网站中使用的解决方法。不幸的是,facebook 还不能很好地识别它,但我会尽快更新。 Angular 11 Meta 标签使用 NET.5 workarround 21/1/2021 12:2:47 使用 NET 5 解决方法的 Angular 11 元标记 https://softease.ro/news/angular-11-meta-tags-using-net-5-workarround

      如何使用特定页面的正确元标记从 .NET 5 提供 Angular SPA。

      1.在你的启动中声明这个中间件。这样做的目的是,当路径是我们知道它必须具有不同元数据的路径时,用正确的元数据重写索引。

        app.Use(async (context, next) =>
                 {
                     await next();
                     if (context.Response.StatusCode == 404 &&
                        !Path.HasExtension(context.Request.Path.Value) &&
                        !context.Request.Path.Value.StartsWith("/api/"))
                     {
                         var path = context.Request.Path;
                         if (path.Value.Contains("/view-product/"))
                         {
                             try
                             {
                                 var idxPath = Path.Combine(env.ContentRootPath, "wwwroot", "index.html");
                                 var index = File.ReadAllText(idxPath);
                                 index = ViewProductService.GetMeta(index, path.Value);
                                 context.Response.StatusCode = 200;
                                 await context.Response.WriteAsync(index);
                                 return;
                             }
                             catch
                             {
                             }
                         }
                         else if (path.Value.Contains("/news/"))
                         {
                             try
                             {
                          
      
         var idxPath = Path.Combine(env.ContentRootPath, "wwwroot", "index.html");
                             var index = File.ReadAllText(idxPath);
                             index = NewsService.GetMeta(index, path.Value);
                             context.Response.StatusCode = 200;
                             await context.Response.WriteAsync(index);
                             return;
                         }
                         catch
                         {
                         }
                     }
                     context.Request.Path = "/index.html";
                     await next();
                 }
             });
      
      1. 您的每个服务都必须使用正确的元数据重写索引。我们以 NewsService GetMeta 为例:

            var res = (from x in UOW.DbContext.News
                           where (x.Id_News.ToString() == newsId || x.PermaLink == newsId)
                           select new IndexMetaModel()
                           {
                               OgTitle = settings.DisplayName + " " + x.Subject,
                               OgDescription = x.ShortDescription,
                               OgUrl = Globals.AppUrl + "/news/" + x.PermaLink + "/"
                           }).FirstOrDefault();
        

      从 db 读取并转换为我们的元模型。在 IndexMetaUtil.ReplaceTags 中运行模型。

      var resIdx = IndexMetaUtil.ReplaceTags(res, index);
      
      return resIdx;
      

      奖金:

      对请求使用缓存:

        if (NewsDomainService.MetaIndex.ContainsKey(path))
             {`enter code here`
                 return NewsDomainService.MetaIndex[path];
             }`enter code here`
      

      IdexMetaUtil:

         public static class IndexMetaUtil
         {
             public static string ReplaceTags(IndexMetaModel meta, string index)
             {
                 HtmlDocument doc = new HtmlDocument();
                 doc.LoadHtml(index);
                 var list = doc.DocumentNode.SelectNodes("//meta");
                 bool vidFound = false;
                 foreach (var node in list)
                 {
                     string property = node.GetAttributeValue("property", "");
                     string value = "";
                     switch (property)
                     {
                         case "og:title":
                             value = meta.OgTitle;
                             node.SetAttributeValue("content", value);
                             break;
                         case "description":
                         case "og:description":
                             var hd = new HtmlDocument();
                             hd.LoadHtml(meta.OgDescription);
                             value = hd.DocumentNode.InnerText;
                             node.SetAttributeValue("content", value);
                             break;
                         case "og:image":
                             if (!vidFound)
                                 value = meta.OgImage;
                             node.SetAttributeValue("content", value);
                             break;
                         case "og:url":
                             value = meta.OgUrl;
                             node.SetAttributeValue("content", value);
                             break;
                     }
                 }
                 return doc.DocumentNode.OuterHtml;
             }
         }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-06-20
        • 2012-12-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多