Skip to content

Commit

Permalink
Merge branch '8094-boilerplate-project-templates-sitemapxml-is-missin…
Browse files Browse the repository at this point in the history
  • Loading branch information
ysmoradi committed Jul 22, 2024
2 parents 8942aee + 3c03c49 commit 4e445a6
Showing 1 changed file with 32 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,8 @@ private static void ConfiureMiddlewares(this WebApplication app)
QueryStringParameter = queryStringParameter
}).WithTags("Test");

app.UseSiteMap();

app.MapControllers().RequireAuthorization();

// Handle the rest of requests with blazor
Expand All @@ -118,6 +120,36 @@ private static void ConfiureMiddlewares(this WebApplication app)
}
}

private static void UseSiteMap(this WebApplication app)
{
var urls = typeof(Urls)
.GetFields()
.Select(f => f.GetValue(null)!.ToString()!)
.ToList()!;

urls = CultureInfoManager.MultilingualEnabled ?
CultureInfoManager.SupportedCultures.SelectMany(sc => urls.Select(url => $"{url}?culture={sc.Culture.Name}")).ToList() :
urls;

const string siteMapHeader = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<urlset\r\n xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\"\r\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\r\n xsi:schemaLocation=\"http://www.sitemaps.org/schemas/sitemap/0.9\r\n http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd\">";

app.MapGet("/sitemap.XML", async context =>
{
if (siteMap is null)
{
var baseUrl = context.Request.GetBaseUrl();

siteMap = $"{siteMapHeader}{string.Join(Environment.NewLine, urls.Select(u => $"<url><loc>{new Uri(baseUrl, u)}</loc></url>"))}</urlset>";
}

context.Response.Headers.ContentType = "application/xml";

await context.Response.WriteAsync(siteMap, context.RequestAborted);
});
}

private static string? siteMap;

/// <summary>
/// Prior to the introduction of .NET 8, the Blazor router effectively managed NotFound and NotAuthorized components during pre-rendering.
/// However, the current behavior has changed, and it now exclusively returns 401, 403, and 404 status codes with an empty body response!
Expand Down

0 comments on commit 4e445a6

Please sign in to comment.