在.net核心中使用angular更新og/meta标签 [英] update og/meta tags with angular in .net core

查看:38
本文介绍了在.net核心中使用angular更新og/meta标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试添加og标签,facebook将从我的网上发现的标签中添加这些标签,这听起来像通用角度现在已合并为角度,应该可以通过使用平台浏览器库来实现.

I am trying to add og tags that facebook will pickup and from what I have found online, it sounds like angular universal is now merged into angular and should be able to do that by using the platform-browser library.

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

I started a brand new .net core project with angular support. It created 3 angular components that I was hoping I could test to try and set the og tags - counter.component.ts, fetchdata.component.ts and home.component.ts. Below is an example of what I have in the counter.component.ts constructor.

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结构中呈现的.

When I run this and view the source it does in fact add the og tags however they're rendered inside it's own html structure within the app tag.

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

我为boot.server.ts文件找到了一些代码,该代码删除了仅保留meta的多余标签,但是由于它们不在实际的头部标签中,因此Facebook的调试器仍然无法将它们拾取.

I found some code for the boot.server.ts file that removes the extra tags leaving just the meta, but because they're not in the actual head tag facebook's debugger still doesn't pick them up.

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

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

Everything I've read makes it sound like this is how it's supposed to work and it's SEO/Social Media friendly. But apparently not. I'm not sure if this is how it's intended to work or if the .net core template isn't set up properly?

推荐答案

我已经尝试过在网站上使用的工作环境.不幸的是,facebook尚不十分清楚,但我一弄清,便会进行更新.使用NET.5 Workarround的Angular 11 Meta标签21/1/2021 12:2:47使用NET 5 Workarround的Angular 11 Meta标签 https://softease.ro/news/angular-11-meta-tags-using-net-5-workarround

I have attempted a workarround that i use in my website. Unfortunately facebook doesn't recognise it very well yet, but i'll come with an update as soon as i will figure it out. Angular 11 Meta tags using NET.5 workarround 21/1/2021 12:2:47 Angular 11 Meta tags using NET 5 workarround https://softease.ro/news/angular-11-meta-tags-using-net-5-workarround

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

How to serve Angular SPA from .NET 5 using the correct meta tags for a specific page.

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

1.In your startup declare this middleware. What this will do, is to rewrite the index with the correct meta when the path is one that we know it must have different meta.

  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. 您的每个服务都必须使用正确的meta重写索引.让我们以NewsService GetMeta为例:

  1. Each of your services, must rewrite the index with the correct meta. Let's take for example 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中运行模型.

Read from db and transform into our meta model. Run the model in the 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:

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;
       }
   }

这篇关于在.net核心中使用angular更新og/meta标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆