通过自定义路由实现百度SiteMap文件

2024-03-01 16:50 小编

1、首先添加一个自定义页面,具体参考相关文档,具体配置可以参考:

  <route urlConstraint="^buildSiteMap.cshtml$"  viewPath="siteMap/siteMap.cshtml" httpcacheSolutionId="0" title=""></route>

以上配置仅供参考,大家可以根据自己需要来写。


2、在模板目录的Views目录下新一个siteMap/siteMap.cshtml文件,文件内容如下:

@{
    Layout = null;
    string table = Request.QueryString["table"];
    string domain = "http://localhost:800/buildSiteMap.cshtml";//localhost:800改为您的网站域名,必须是外网域名
    
    //生成栏目siteMap
    if (table=="column")
    {
        <?xml version="1.0" encoding="utf-8" ?>
          <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">
            @foreach (var item in Html.GetColumnList().Where(c => c.Show == 1 && c.ColumnType <= 2))
            {
            string url = Html.ColumnUrl((int)(item.Id));
                <url>
                    <mobile:mobile type="pc,mobile" />
                    <loc>@url</loc>
                    <lastmod>@DateTime.Now.ToString("yyyy-MM-dd")</lastmod>
                    <changefreq>weekly</changefreq>
                    <priority>0.8</priority>
                </url>
            }
        </urlset>
        }
    //生成信息表的siteMap
    else if (!string.IsNullOrEmpty(table))
    {
            <?xml version="1.0" encoding="utf-8" ?>
                    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
                        @foreach (var item in Html.InfoDataList(new { Table = table, ShowNumber = 1500 }))
                        {
                            <url>
                                <mobile:mobile type="pc,mobile" />
                                <loc>http://www.pageadmin.net/jianzhan/@(item.Id).cshtml</loc>
                                <lastmod>@item.Thedate.ToString("yyyy-MM-dd")</lastmod>
                                <changefreq>weekly</changefreq>
                                <priority>0.5</priority>
                            </url>
                        }
    }
                    </urlset>
    }
    else
    {
        HttpRequestHelper httpRequestHelper = new HttpRequestHelper();
        //生成栏目siteMap文件
        IOHelper.CreateFile("/columnSiteMap.xml", httpRequestHelper.Get(domain+"?table=column").Trim(), true);
        //生成product表的siteMap文件,必须保证news信息表实际存在
        IOHelper.CreateFile("/productSiteMap.xml", httpRequestHelper.Get(domain+"?table=product").Trim(), true);
        //生成news表的siteMap文件,必须保证news信息表实际存在
        IOHelper.CreateFile("/newsSiteMap.xml", httpRequestHelper.Get(domain+"?table=news").Trim(), true);
        //更多信息表可以自行添加IOHelper.CreateFile方法,table参数改为信息表名即可
        Response.Write("sitemap文件生成成功!");
    }

}

3、最后直接在浏览器中输入:您的域名/buildSiteMap.cshtml 就会自动生成对应siteMap.xml文件,生成后在百度站长工具提交即可。


在线咨询 拨打电话

电话

13363039260

微信二维码

微信二维码