实际上,我更喜欢使用Razor. 假设您只有一页,.NET Core 3.1 中的示例代码将如下所示(.NET Core 2 代码不会有太大不同):
<!-- XmlSitemap.cshtml -->
@page "/sitemap.xml"
@using Microsoft.AspNetCore.Http
@{
var pages = new List<dynamic>
{
new { Url = "http://example.com/", LastUpdated = DateTime.Now }
};
Layout = null;
Response.ContentType = "text/xml";
await Response.WriteAsync("<?xml version='1.0' encoding='UTF-8' ?>");
}
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
@foreach (var page in pages)
{
<url>
<loc>@page.Url</loc>
<lastmod>@page.LastUpdated.ToString("yyyy-MM-dd")</lastmod>
</url>
}
</urlset>
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
我从正在处理的示例Web应用程序中找到了您问题的解决方案。幸得的Mads克里斯滕森。这是您正在寻找的非常简化的版本。将此代码放在与HomeController之类的控制器类中的方式与添加操作方法的方式相同。
这是返回XML的方法:
[Route("/sitemap.xml")]
public void SitemapXml()
{
string host = Request.Scheme + "://" + Request.Host;
Response.ContentType = "application/xml";
using (var xml = XmlWriter.Create(Response.Body, new XmlWriterSettings { Indent = true }))
{
xml.WriteStartDocument();
xml.WriteStartElement("urlset", "http://www.sitemaps.org/schemas/sitemap/0.9");
xml.WriteStartElement("url");
xml.WriteElementString("loc", host);
xml.WriteEndElement();
xml.WriteEndElement();
}
}
Run Code Online (Sandbox Code Playgroud)
当您输入时,将产生以下内容http://www.example.com/sitemap.xml:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.example.com/</loc>
</url>
</urlset>
Run Code Online (Sandbox Code Playgroud)
我希望这有帮助?如果您还发现了一些问题,请发布您的解决方案以更新问题。
幸运的是,已经有一个预先构建的库列表。安装此工具https://github.com/uhaciogullari/SimpleMvcSitemap
然后像这样创建一个新的控制器(github上有更多示例):
public class SitemapController : Controller
{
public ActionResult Index()
{
List<SitemapNode> nodes = new List<SitemapNode>
{
new SitemapNode(Url.Action("Index","Home")),
new SitemapNode(Url.Action("About","Home")),
//other nodes
};
return new SitemapProvider().CreateSitemap(new SitemapModel(nodes));
}
}
Run Code Online (Sandbox Code Playgroud)
中间件工作正常,但需要进行较小的修复。
if (context.Request.Path.Value.Equals("/sitemap.xml", StringComparison.OrdinalIgnoreCase))
{
// Implementation
}
else
await _next(context);
Run Code Online (Sandbox Code Playgroud)
我创建了一个新项目,然后添加了中间件并运行后,在浏览器中输入了http:// localhost:64522 / sitemap.xml,得到了以下结果:
<?xml version="1.0" encoding="utf-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://localhost:64522/home/index</loc>
<lastmod>2018-05-13</lastmod>
</url>
<url>
<loc>http://localhost:64522/home/about</loc>
<lastmod>2018-05-13</lastmod>
</url>
<url>
<loc>http://localhost:64522/home/contact</loc>
<lastmod>2018-05-13</lastmod>
</url>
<url>
<loc>http://localhost:64522/home/privacy</loc>
<lastmod>2018-05-13</lastmod>
</url>
<url>
<loc>http://localhost:64522/home/error</loc>
<lastmod>2018-05-13</lastmod>
</url>
</urlset>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4816 次 |
| 最近记录: |