使用servicestack angular 2模板在服务器上呈现seo meta标签

时间:2017-07-02 14:19:15

标签: angular servicestack

Servicestack angular 2模板只有一个入口点--inxed.html。 假设我们希望在服务器上呈现seo meta标签,以便为/ product / id等路由进行SEO优化。任何想法如何制作?

1 个答案:

答案 0 :(得分:2)

ServiceStack的Single Page App templates顾名思义只从单个服务器index.html页面运行。这意味着所有路由都在Angular JS中的客户端(即浏览器)上执行。

这意味着当客户端导航到网站上的其他页面时,例如到/products/1请求由Angular客户端路由处理,以加载已配置的组件,即请求永远不会到达服务器。

但是当向/products/1发出初始请求时,请求将发送到服务器,但为了使Angular能够处理客户端上的路由,ServiceStack将返回index.html家页面,它使用模板FallbackRoute中配置的MyServices class对任何不匹配的请求执行此操作,例如

[Exclude(Feature.Metadata)]
[FallbackRoute("/{PathInfo*}")]
public class FallbackForClientRoutes
{
    public string PathInfo { get; set; }
}

public class MyServices : Service
{
    //Return index.html for unmatched requests so routing is handled on client
    public object Any(FallbackForClientRoutes request) =>
        new HttpResult(VirtualFileSources.GetFile("index.html"));
}

为了能够返回修改后的index.html页面,您只需创建一个与您要处理的请求相匹配的路线,例如:

[Exclude(Feature.Metadata)] //Hide Route from metadata pages
[Route("/product/{Id}")]
public class ViewProduct
{
    public int Id { get; set; }
}

并返回修改后的index.html页面,用您想要的元数据替换页面中的占位符,例如:

[AddHeader(ContentType = MimeTypes.Html)]
public object Any(ViewProduct request)
{
    var indexFile = VirtualFileSources.GetFile("index.html");
    var html = indexFile.ReadAllText();
    return html.Replace("meta name=\"description\"", 
       $"meta name=\"description\" content=\"Product #{request.Id}\"");
}

要告诉Webpack在生成index.html时需要修改index.template.ejs模板,请包含自定义占位符,例如:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description">
 ...