提供动态 sitemap.xml 内容
Serving dynamic sitemap.xml content
如何从 ASP.NET Core 3.1 提供动态 sitemap.xml
文件?
我试过类似的方法:
...
public ActionResult SiteMap()
{
// logic here
return Content("<sitemap>...</sitemap>", "text/xml");
}
...
是的,这正是正确的方法。当然,假设您使用的是 standard sitemap protocol,您需要:
- 建立XML声明(例如
<?xml version="1.0" encoding="UTF-8"?>
)
- 从
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />
元素开始
因此,例如,如果您想使用 XDocument
组装 XML,您可以从以下内容开始:
private static readonly XNamespace _sitemapNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9";
private static readonly XNamespace _pagemapNamespace = "http://www.google.com/schemas/sitemap-pagemap/1.0";
public ActionResult Sitemap() {
var xml = new XDocument(
new XDeclaration("1.0", "utf-8", String.Empty),
new XElement(_sitemapNamespace + "urlset",
//Your logic here
)
return Content(sitemap.ToString(), "text/xml");
);
}
也就是说,使用此代码,您将 运行 遇到 XML 声明未随 XML 一起返回的问题,因为 XDocument.ToString()
仅 returns 一个 XML 片段。要解决此问题,您需要将 XDocument
包装在例如一个 StringWriter
:
var sitemapFile = new StringBuilder();
using (var writer = new StringWriter(sitemapFile)) {
sitemap.Save(writer);
}
return Content(sitemapFile.ToString(), "text/xml");
Note: There are obviously other approaches for dynamically generating your XML. If you're using an XmlWriter
or an XmlDocument
, your code will look quite different. The point is to help fill out what a real-world implementation might look like, not to prescribe an exclusive approach.
您在尝试时 运行 是否遇到了具体问题?如果是这样,我也许可以提供更具体的指导。但是,实际上,您采用的方法是正确的。
如何从 ASP.NET Core 3.1 提供动态 sitemap.xml
文件?
我试过类似的方法:
...
public ActionResult SiteMap()
{
// logic here
return Content("<sitemap>...</sitemap>", "text/xml");
}
...
是的,这正是正确的方法。当然,假设您使用的是 standard sitemap protocol,您需要:
- 建立XML声明(例如
<?xml version="1.0" encoding="UTF-8"?>
) - 从
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" />
元素开始
因此,例如,如果您想使用 XDocument
组装 XML,您可以从以下内容开始:
private static readonly XNamespace _sitemapNamespace = "http://www.sitemaps.org/schemas/sitemap/0.9";
private static readonly XNamespace _pagemapNamespace = "http://www.google.com/schemas/sitemap-pagemap/1.0";
public ActionResult Sitemap() {
var xml = new XDocument(
new XDeclaration("1.0", "utf-8", String.Empty),
new XElement(_sitemapNamespace + "urlset",
//Your logic here
)
return Content(sitemap.ToString(), "text/xml");
);
}
也就是说,使用此代码,您将 运行 遇到 XML 声明未随 XML 一起返回的问题,因为 XDocument.ToString()
仅 returns 一个 XML 片段。要解决此问题,您需要将 XDocument
包装在例如一个 StringWriter
:
var sitemapFile = new StringBuilder();
using (var writer = new StringWriter(sitemapFile)) {
sitemap.Save(writer);
}
return Content(sitemapFile.ToString(), "text/xml");
Note: There are obviously other approaches for dynamically generating your XML. If you're using an
XmlWriter
or anXmlDocument
, your code will look quite different. The point is to help fill out what a real-world implementation might look like, not to prescribe an exclusive approach.
您在尝试时 运行 是否遇到了具体问题?如果是这样,我也许可以提供更具体的指导。但是,实际上,您采用的方法是正确的。