-
-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathSitemapController.cs
52 lines (46 loc) · 1.62 KB
/
SitemapController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
using System;
using System.IO;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using LinkDotNet.Blog.Web.Features.Admin.Sitemap.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.RateLimiting;
using Microsoft.Extensions.Caching.Memory;
namespace LinkDotNet.Blog.Web.Controller;
[EnableRateLimiting("ip")]
[Route("sitemap.xml")]
public sealed class SitemapController : ControllerBase
{
private readonly ISitemapService sitemapService;
private readonly IXmlWriter xmlWriter;
private readonly IMemoryCache memoryCache;
public SitemapController(
ISitemapService sitemapService,
IXmlWriter xmlWriter,
IMemoryCache memoryCache)
{
this.sitemapService = sitemapService;
this.xmlWriter = xmlWriter;
this.memoryCache = memoryCache;
}
[ResponseCache(Duration = 3600)]
[HttpGet]
public async Task<IActionResult> GetSitemap()
{
var buffer = await memoryCache.GetOrCreateAsync("sitemap.xml", async e =>
{
e.AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(1);
return await GetSitemapBuffer();
})
?? throw new InvalidOperationException("Buffer is null");
return File(buffer, "application/xml");
}
private async Task<byte[]> GetSitemapBuffer()
{
var baseUri = $"{Request.Scheme}://{Request.Host}{Request.PathBase}";
var sitemap = await sitemapService.CreateSitemapAsync(baseUri);
var buffer = await xmlWriter.WriteToBuffer(sitemap);
return buffer;
}
}