Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 如何在.NET core 2中动态创建sitemap.xml?_Asp.net_Asp.net Core_Sitemap_.net Core 2.0 - Fatal编程技术网

Asp.net 如何在.NET core 2中动态创建sitemap.xml?

Asp.net 如何在.NET core 2中动态创建sitemap.xml?,asp.net,asp.net-core,sitemap,.net-core-2.0,Asp.net,Asp.net Core,Sitemap,.net Core 2.0,有人能告诉我如何在.NETCore2中创建站点地图吗 这些/在.NET Core 2中不起作用。中间件工作正常,但需要一个小的修复 if (context.Request.Path.Value.Equals("/sitemap.xml", StringComparison.OrdinalIgnoreCase)) { // Implementation } else await _next(context); 我创建了一个新项目,然后在添加中间件并运行之后,我进入浏览器,得到以下

有人能告诉我如何在.NETCore2中创建站点地图吗


这些/在.NET Core 2中不起作用。

中间件工作正常,但需要一个小的修复

if (context.Request.Path.Value.Equals("/sitemap.xml", StringComparison.OrdinalIgnoreCase))
{
    // Implementation
}
else
    await _next(context);
我创建了一个新项目,然后在添加中间件并运行之后,我进入浏览器,得到以下结果:

<?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>

http://localhost:64522/home/index
2018-05-13
http://localhost:64522/home/about
2018-05-13
http://localhost:64522/home/contact
2018-05-13
http://localhost:64522/home/privacy
2018-05-13
http://localhost:64522/home/error
2018-05-13

幸运的是,已经有了一个预构建库的列表。安装此工具

然后像这样创建一个新控制器(github上有更多示例):

公共类SitemapController:控制器
{
公共行动结果索引()
{
列表节点=新列表
{
新的SitemapNode(Url.Action(“索引”、“主页”),
新建SitemapNode(Url.Action(“关于”,“主页”),
//其他节点
};
返回新的SitemapProvider().CreateSitemap(新的SitemapModel(节点));
}
}

我从正在使用的示例web应用程序中找到了您问题的解决方案。功劳归于我。这是一个非常简单的版本,你正在寻找。将此代码放入类似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();
     }
}
当您键入
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>

http://www.example.com/
我希望这有帮助?如果您还发现了一些问题,请将您的解决方案作为问题的更新发布。

动态站点地图“sitemap blog.xml”用于博客部分和24小时缓存。(ASP.NET核心3.1)

  • sitemap.xml存在于wwwroot(由xml-sitemaps.com或…)中
  • sitemap blog.xml动态生成
robots.txt

User-agent: *
Disallow: /Admin/
Disallow: /Identity/
Sitemap: https://example.com/sitemap.xml
Sitemap: https://example.com/sitemap-blog.xml
Startup.cs

services.AddMemoryCache();
namespace MT.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IMemoryCache _cache;

        public HomeController(
            ApplicationDbContext context,
            IMemoryCache cache)
        {
            _context = context;
            _cache = cache;

        }

        [Route("/sitemap-blog.xml")]
        public async Task<IActionResult> SitemapBlog()
        {
            string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
            string segment = "blog";
            string contentType = "application/xml";

            string cacheKey = "sitemap-blog.xml";

            // For showing in browser (Without download)
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = cacheKey,
                Inline = true,
            };
            Response.Headers.Append("Content-Disposition", cd.ToString());

            // Cache
            var bytes = _cache.Get<byte[]>(cacheKey);
            if (bytes != null)
                return File(bytes, contentType);

            var blogs = await _context.Blogs.ToListAsync();

            var sb = new StringBuilder();
            sb.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");
            sb.AppendLine($"   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
            sb.AppendLine($"   xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">");

            foreach (var m in blogs)
            {
                var dt = m.LastModified;
                string lastmod = $"{dt.Year}-{dt.Month.ToString("00")}-{dt.Day.ToString("00")}";

                sb.AppendLine($"    <url>");

                sb.AppendLine($"        <loc>{baseUrl}/{segment}/{m.Slug}</loc>");
                sb.AppendLine($"        <lastmod>{lastmod}</lastmod>");
                sb.AppendLine($"        <changefreq>daily</changefreq>");
                sb.AppendLine($"        <priority>0.8</priority>");

                sb.AppendLine($"    </url>");
            }

            sb.AppendLine($"</urlset>");

            bytes = Encoding.UTF8.GetBytes(sb.ToString());

            _cache.Set(cacheKey, bytes, TimeSpan.FromHours(24));
            return File(bytes, contentType);
        }
    }
}
HomeController.cs

services.AddMemoryCache();
namespace MT.Controllers
{
    public class HomeController : Controller
    {
        private readonly ApplicationDbContext _context;
        private readonly IMemoryCache _cache;

        public HomeController(
            ApplicationDbContext context,
            IMemoryCache cache)
        {
            _context = context;
            _cache = cache;

        }

        [Route("/sitemap-blog.xml")]
        public async Task<IActionResult> SitemapBlog()
        {
            string baseUrl = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
            string segment = "blog";
            string contentType = "application/xml";

            string cacheKey = "sitemap-blog.xml";

            // For showing in browser (Without download)
            var cd = new System.Net.Mime.ContentDisposition
            {
                FileName = cacheKey,
                Inline = true,
            };
            Response.Headers.Append("Content-Disposition", cd.ToString());

            // Cache
            var bytes = _cache.Get<byte[]>(cacheKey);
            if (bytes != null)
                return File(bytes, contentType);

            var blogs = await _context.Blogs.ToListAsync();

            var sb = new StringBuilder();
            sb.AppendLine($"<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"");
            sb.AppendLine($"   xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
            sb.AppendLine($"   xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">");

            foreach (var m in blogs)
            {
                var dt = m.LastModified;
                string lastmod = $"{dt.Year}-{dt.Month.ToString("00")}-{dt.Day.ToString("00")}";

                sb.AppendLine($"    <url>");

                sb.AppendLine($"        <loc>{baseUrl}/{segment}/{m.Slug}</loc>");
                sb.AppendLine($"        <lastmod>{lastmod}</lastmod>");
                sb.AppendLine($"        <changefreq>daily</changefreq>");
                sb.AppendLine($"        <priority>0.8</priority>");

                sb.AppendLine($"    </url>");
            }

            sb.AppendLine($"</urlset>");

            bytes = Encoding.UTF8.GetBytes(sb.ToString());

            _cache.Set(cacheKey, bytes, TimeSpan.FromHours(24));
            return File(bytes, contentType);
        }
    }
}
名称空间MT.控制器
{
公共类HomeController:控制器
{
私有只读应用程序的bContext\u上下文;
专用只读IMemoryCache\u缓存;
公共家庭控制器(
ApplicationDbContext上下文,
IMemoryCache缓存)
{
_上下文=上下文;
_缓存=缓存;
}
[路线(“/sitemap blog.xml”)]
公共异步任务SitemapBlog()
{
字符串baseUrl=$“{Request.Scheme}://{Request.Host}{Request.PathBase}”;
string segment=“blog”;
字符串contentType=“应用程序/xml”;
string cacheKey=“sitemap blog.xml”;
//用于在浏览器中显示(无需下载)
var cd=new System.Net.Mime.ContentDisposition
{
FileName=cacheKey,
Inline=true,
};
Append(“内容处置”,cd.ToString());
//缓存
var bytes=\u cache.Get(cacheKey);
如果(字节数!=null)
返回文件(字节、内容类型);
var blogs=await_context.blogs.ToListAsync();
var sb=新的StringBuilder();
某人加上一行($);
某人加上一行($);
foreach(博客中的var m)
{
var dt=m.LastModified;
字符串lastmod=$“{dt.Year}-{dt.Month.ToString(“00”)}-{dt.Day.ToString(“00”);
某人加上一行($);
sb.AppendLine($“{baseUrl}/{segment}/{m.Slug}”);
sb.AppendLine($“{lastmod}”);
sb.追加行($“每日”);
sb.附加线("0.8元);;
某人加上一行($);
}
某人加上一行($);
字节=Encoding.UTF8.GetBytes(sb.ToString());
_Set(cacheKey,bytes,TimeSpan.FromHours(24));
返回文件(字节、内容类型);
}
}
}

实际上,我更喜欢使用
Razor
将其写入模板文件。假设您只有一个页面,.NET Core 3.1中的示例代码如下所示(.NET Core 2代码不会有太大不同):


@页面“/sitemap.xml”
@使用Microsoft.AspNetCore.Http
@{
var pages=新列表
{
新的{Url=”http://example.com/,LastUpdated=DateTime.Now}
};
布局=空;
Response.ContentType=“text/xml”;
等待响应。WriteAsync(“”);
}
@foreach(页面中的变量页面)
{
@页面Url
@page.LastUpdated.ToString(“yyyy-MM-dd”)
}

希望这有帮助

让我们采取两种方法来达到预期的结果

首先,这些文章使用中间件方法。使用控制器和
SimpleMvcSitemap

把它们放在一起,我们就有了这个代码

/// <summary>
/// Base URL Provider for sitemap. Replace with your domain
/// </summary>
public class BaseUrlProvider : IBaseUrlProvider
{
    public Uri BaseUrl => new Uri("https://example.com");
}

public class SitemapController : Controller
{

    [Route("sitemap.xml")]
    public ActionResult Index()
    {
        List<SitemapNode> nodes = new List<SitemapNode>();


        // get available contrtollers
        var controllers = Assembly.GetExecutingAssembly().GetTypes()
                .Where(type => typeof(Controller).IsAssignableFrom(type)
                || type.Name.EndsWith("controller")).ToList();

        foreach (var controller in controllers)
        {
            // get available methods
            var methods = controller.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
                .Where(method => typeof(IActionResult).IsAssignableFrom(method.ReturnType));

            foreach (var method in methods)
            {
                // add route name in sitemap
                nodes.Add(new SitemapNode(Url.Action(method.Name, controllerName)));
            }
        }

        return new SitemapProvider(new BaseUrlProvider()).CreateSitemap(new SitemapModel(nodes));
    }
}
最后只开放路线,例如:

https://localhost:44312/sitemap.xml

如果您使用的是.net core 2及更高版本,请执行以下操作:

将其添加到.csproj文件

然后在Program.cs文件中添加引用 使用X.Web.Sitemap

在Program.cs文件中,在Main方法中执行以下操作:
主要方法是:

private static Url CreateUrl(string url)
          {
               return new Url
               {
                    ChangeFrequency = ChangeFrequency.Daily,
                    Location = url,
                    Priority = 0.5,
                    TimeStamp = DateTime.Now
               };
          }

下面的代码适用于ASP.NET Core 2.2

公共类SitemapUrl
{
公共字符串页{get;set;}
公共日期时间?LastModifyed{get;set;}
/*
总是
每小时
每日的
每周的
月刊
每年的
从未
*/
公共字符串ChangeFreq{get;set;}
公共浮点优先级{get;set;}=0.5f;
}
公共类SitemapResult:ActionResult
{
私有只读IEnumerable\u URL;
公共站点映射结果(
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Microsoft.AspNetCore.Mvc;
using SimpleMvcSitemap;
using SimpleMvcSitemap.Routing;
https://localhost:44312/sitemap.xml
var sitemap = new Sitemap();

               sitemap.Add(new Url
               {
                    ChangeFrequency = ChangeFrequency.Daily,
                    Location = "https://www.website.com",
                    Priority = 0.5,
                    TimeStamp = DateTime.Now
               });

               sitemap.Add(CreateUrl("https://www.website.com/about"));
               sitemap.Add(CreateUrl("https://www.website.com/services"));
               sitemap.Add(CreateUrl("https://www.website.com/products"));
               sitemap.Add(CreateUrl("https://www.website.com/casestudies"));
               sitemap.Add(CreateUrl("https://www.website.com/blogs"));
               sitemap.Add(CreateUrl("https://www.website.com/contact"));

               //Save sitemap structure to file
               sitemap.Save(@"wwwroot\sitemap.xml");

               //Split a large list into pieces and store in a directory
               //sitemap.SaveToDirectory(@"d:\www\summituniversity.edu.ng\sitemaps");

               //Get xml-content of file
               Console.Write(sitemap.ToXml());
               Console.ReadKey();
private static Url CreateUrl(string url)
          {
               return new Url
               {
                    ChangeFrequency = ChangeFrequency.Daily,
                    Location = url,
                    Priority = 0.5,
                    TimeStamp = DateTime.Now
               };
          }
public IActionResult Sitemap(){
    return new SitemapResult(new SitemapUrl[] { new SitemapUrl() { } });
}
app.UseSitemap();
// All routes in this controller will be ignored
[SitemapExclude]
public class BlahController : Controller
{
    [Route("some-route")]
    public IActionResult Something()
    {
        return View();
    }
}

public class BlahController : Controller
{
    [SitemapExclude]
    [Route("some-route")]
    public IActionResult Ignored()
    {
        return View();
    }

    [Route("some-other-route")]
    public IActionResult NotIgnored()
    {  
        return View();
    }
}