From 36cfffe106cc122148e2624035c52f4db660a1e9 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Fri, 16 Oct 2026 17:56:18 -0700 Subject: [PATCH 1/3] feat(seo): add per-page descriptions and canonical metadata --- .../ChapterDescriptionServiceTests.cs | 45 ++++++++++++++++++ EssentialCSharp.Web.Tests/FunctionalTests.cs | 44 +++++++++++++++++ .../Controllers/HomeController.cs | 14 +++++- .../Controllers/McpSetupController.cs | 1 + EssentialCSharp.Web/Program.cs | 1 + .../Services/ChapterDescriptionService.cs | 47 +++++++++++++++++++ .../Views/Shared/_Layout.cshtml | 17 +++++-- README.md | 6 +++ 8 files changed, 171 insertions(+), 4 deletions(-) create mode 100644 EssentialCSharp.Web.Tests/ChapterDescriptionServiceTests.cs create mode 100644 EssentialCSharp.Web/Services/ChapterDescriptionService.cs diff --git a/EssentialCSharp.Web.Tests/ChapterDescriptionServiceTests.cs b/EssentialCSharp.Web.Tests/ChapterDescriptionServiceTests.cs new file mode 100644 index 00000000..9ba41312 --- /dev/null +++ b/EssentialCSharp.Web.Tests/ChapterDescriptionServiceTests.cs @@ -0,0 +1,45 @@ +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Hosting; +using Moq; + +namespace EssentialCSharp.Web.Tests; + +public class ChapterDescriptionServiceTests +{ + [Test] + public async Task GeneratedDescriptionsOverrideHeadingFallback() + { + string directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); + Directory.CreateDirectory(Path.Combine(directory, "Chapters")); + try + { + File.WriteAllText(Path.Combine(directory, "Chapters", "sitemap.descriptions.json"), + """[{"Keys":["example-page","alias"],"Value":"A tailored chapter description."}]"""); + Mock environment = new(); + environment.SetupGet(e => e.ContentRootPath).Returns(directory); + ChapterDescriptionService service = new(environment.Object); + SiteMapping mapping = CreateMapping("alias", "Examples"); + + await Assert.That(service.GetDescription(mapping)).IsEqualTo("A tailored chapter description."); + await Assert.That(service.GetDescription(CreateMapping("missing", "Other Examples"))).Contains("Other Examples"); + } + finally + { + Directory.Delete(directory, recursive: true); + } + } + + [Test] + public async Task WithoutGeneratedDescriptionsUsesPageHeading() + { + Mock environment = new(); + environment.SetupGet(e => e.ContentRootPath).Returns(Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString())); + ChapterDescriptionService service = new(environment.Object); + + await Assert.That(service.GetDescription(CreateMapping("sample", "Sample Heading"))).Contains("Sample Heading"); + } + + private static SiteMapping CreateMapping(string key, string heading) => + new([key], key, ["Chapters", "01", "Pages", "01.html"], 1, 1, 1, + "Chapter One", heading, null, 1); +} diff --git a/EssentialCSharp.Web.Tests/FunctionalTests.cs b/EssentialCSharp.Web.Tests/FunctionalTests.cs index 9d460476..08e99ab4 100644 --- a/EssentialCSharp.Web.Tests/FunctionalTests.cs +++ b/EssentialCSharp.Web.Tests/FunctionalTests.cs @@ -1,4 +1,5 @@ using System.Net; +using HtmlAgilityPack; namespace EssentialCSharp.Web.Tests; @@ -42,6 +43,49 @@ public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl) await Assert.That(content).Contains(" logger, IWebHostEnvironment hostingEnvironment, ISiteMappingService siteMappingService, IHttpContextAccessor httpContextAccessor, IRouteConfigurationService routeConfigurationService, IOptions siteSettings) : BaseController(routeConfigurationService, httpContextAccessor) +public class HomeController(ILogger logger, IWebHostEnvironment hostingEnvironment, ISiteMappingService siteMappingService, ChapterDescriptionService chapterDescriptionService, IHttpContextAccessor httpContextAccessor, IRouteConfigurationService routeConfigurationService, IOptions siteSettings) : BaseController(routeConfigurationService, httpContextAccessor) { [EnableRateLimiting("content")] public IActionResult Index() @@ -42,8 +42,15 @@ public IActionResult Index() } string headHtml = doc.DocumentNode.Element("html")?.Element("head")?.InnerHtml ?? string.Empty; string html = doc.DocumentNode.Element("html")?.Element("body")?.InnerHtml ?? string.Empty; + HtmlNode? canonical = doc.DocumentNode.SelectSingleNode("/html/head/link[@rel='canonical']"); ViewBag.PageTitle = siteMapping.IndentLevel is 0 ? siteMapping.ChapterTitle + " " + siteMapping.RawHeading : siteMapping.RawHeading; + ViewData["Description"] = chapterDescriptionService.GetDescription(siteMapping); + if (canonical is not null) + { + ViewData["CanonicalUrl"] = canonical.GetAttributeValue("href", ""); + ViewData["HeadHasCanonical"] = true; + } ViewBag.NextPage = FlipPage(siteMapping!.ChapterNumber, siteMapping.PageNumber, true); ViewBag.CurrentPageKey = siteMapping.PrimaryKey; ViewBag.PreviousPage = FlipPage(siteMapping.ChapterNumber, siteMapping.PageNumber, false); @@ -63,6 +70,7 @@ public IActionResult Index() public IActionResult TermsOfService() { ViewBag.PageTitle = "Terms Of Service"; + ViewData["Description"] = "Read the terms of service for using Essential C# and its online C# learning resources."; return View(); } @@ -77,6 +85,7 @@ public IActionResult CookiePolicy() public IActionResult Announcements() { ViewBag.PageTitle = "Announcements"; + ViewData["Description"] = "Read the latest Essential C# announcements, updates, and news about the online C# guide."; return View(); } @@ -84,12 +93,14 @@ public IActionResult Announcements() public IActionResult About() { ViewBag.PageTitle = "About"; + ViewData["Description"] = "Learn about Essential C#, the free online C# tutorial and reference by Mark Michaelis and Benjamin Michaelis."; return View(); } [Route("/home", Name = "home")] public IActionResult Home() { + ViewData["Description"] = "Explore Essential C#, a free online C# tutorial and reference with practical examples for developers."; return View(); } @@ -97,6 +108,7 @@ public IActionResult Home() public IActionResult Guidelines() { ViewBag.PageTitle = "Coding Guidelines"; + ViewData["Description"] = "Explore Essential C# coding guidelines and best practices for writing clear, maintainable C#."; FileInfo fileInfo = new(Path.Join(hostingEnvironment.ContentRootPath, "Guidelines", "guidelines.json")); if (!fileInfo.Exists) { diff --git a/EssentialCSharp.Web/Controllers/McpSetupController.cs b/EssentialCSharp.Web/Controllers/McpSetupController.cs index 36efc731..dec801dd 100644 --- a/EssentialCSharp.Web/Controllers/McpSetupController.cs +++ b/EssentialCSharp.Web/Controllers/McpSetupController.cs @@ -21,6 +21,7 @@ public McpSetupController(IRouteConfigurationService routeConfigurationService, public IActionResult Index() { ViewBag.PageTitle = "MCP Setup"; + ViewData["Description"] = "Connect AI coding tools to Essential C# with the Model Context Protocol setup guide."; var toolInfos = _tools .OrderBy(t => t.ProtocolTool.Name) .Select(t => diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 198f68ea..1cb4de2a 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -267,6 +267,7 @@ private static void Main(string[] args) builder.Services.AddOutputCache(); builder.Services.AddCaptchaService(builder.Configuration.GetSection(CaptchaOptions.CaptchaSender)); builder.Services.AddSingleton(); + builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); builder.Services.AddSingleton(); diff --git a/EssentialCSharp.Web/Services/ChapterDescriptionService.cs b/EssentialCSharp.Web/Services/ChapterDescriptionService.cs new file mode 100644 index 00000000..48fa519c --- /dev/null +++ b/EssentialCSharp.Web/Services/ChapterDescriptionService.cs @@ -0,0 +1,47 @@ +using System.Text.Json; + +namespace EssentialCSharp.Web.Services; + +public sealed class ChapterDescriptionService +{ + private readonly Dictionary _Descriptions; + + public ChapterDescriptionService(IWebHostEnvironment environment) + { + string path = Path.Combine(environment.ContentRootPath, "Chapters", "sitemap.descriptions.json"); + if (!File.Exists(path)) + { + _Descriptions = new Dictionary(); + return; + } + + using FileStream stream = File.OpenRead(path); + List entries = JsonSerializer.Deserialize>(stream) + ?? throw new InvalidDataException($"No chapter descriptions found in {path}"); + Dictionary descriptions = new(StringComparer.OrdinalIgnoreCase); + foreach (ChapterDescription entry in entries) + { + foreach (string key in entry.Keys) + { + descriptions.Add(key, entry.Value); + } + } + _Descriptions = descriptions; + } + + public string GetDescription(SiteMapping mapping) + { + foreach (string key in mapping.Keys) + { + if (_Descriptions.TryGetValue(key, out string? description) && !string.IsNullOrWhiteSpace(description)) + { + return description; + } + } + + string heading = mapping.IndentLevel == 0 ? mapping.ChapterTitle : mapping.RawHeading; + return $"Learn about {heading} in Essential C# with practical examples and explanations from the online C# guide."; + } + + private sealed record ChapterDescription(List Keys, string Value); +} diff --git a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml index b209aab4..3dc7b1c3 100644 --- a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml +++ b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml @@ -12,24 +12,35 @@ @inject SignInManager SignInManager @inject IConfiguration Configuration @inject IOptions _CaptchaOptions +@inject IOptions SiteSettings @{ const string imageUrl = "https://essentialcsharp.com/images/icon.png"; - const string description = "Accelerate your development knowledge with C# expert Mark Michaelis and Benjamin Michaelis' free, online comprehensive C# tutorial and reference that is updated through C# 11.0"; + const string defaultDescription = "Accelerate your development knowledge with C# expert Mark Michaelis and Benjamin Michaelis' free, online comprehensive C# tutorial and reference that is updated through C# 11.0"; + string description = ViewData["Description"] is string pageDescription && !string.IsNullOrWhiteSpace(pageDescription) + ? pageDescription + : defaultDescription; + string canonicalUrl = ViewData["CanonicalUrl"] as string + ?? $"{SiteSettings.Value.BaseUrl.TrimEnd('/')}{Context.Request.PathBase}{Context.Request.Path}"; string title = $"Essential C#{(string.IsNullOrEmpty(ViewBag.PageTitle) ? string.Empty : $": {ViewBag.PageTitle}")}"; } - + + @if (ViewData["HeadHasCanonical"] is not true && Context.Response.StatusCode < 400 && !Context.Request.Path.StartsWithSegments("/Identity")) + { + + } @title - + + diff --git a/README.md b/README.md index 071bc6ad..3ae4ddd4 100644 --- a/README.md +++ b/README.md @@ -10,4 +10,10 @@ For any bugs, questions, or anything else with specifically the code found insid For information on setting up your local development environment, please see the [Getting Started Guide](docs/getting-started.md). +## Page metadata + +The shared layout uses `ViewData["Description"]` for the HTML, Open Graph, and Twitter descriptions; pages without an override use the site-wide fallback. Public page actions set their own descriptions. Chapter pages use `Chapters/sitemap.descriptions.json` when available (generated by ParserCli), or a description based on the chapter heading when the file is absent. Views can also set `ViewData["Description"]` before the layout renders. + +Parser-generated chapter HTML supplies its canonical link; other public pages get a canonical link from the layout. Open Graph URLs follow the canonical URL, with `SiteSettings:BaseUrl` and the request path used when no chapter canonical is available. Query strings are excluded. + Please use issues or discussions to report issues found. From c3b1d469be5581a8938c1cd70d6a8f2d82a624d6 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Fri, 16 Oct 2026 17:58:20 -0700 Subject: [PATCH 2/3] fix(seo): cover cookie policy and updated test host --- EssentialCSharp.Web.Tests/FunctionalTests.cs | 25 +++++++++++-------- .../Controllers/HomeController.cs | 1 + 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/EssentialCSharp.Web.Tests/FunctionalTests.cs b/EssentialCSharp.Web.Tests/FunctionalTests.cs index 08e99ab4..a3698e9d 100644 --- a/EssentialCSharp.Web.Tests/FunctionalTests.cs +++ b/EssentialCSharp.Web.Tests/FunctionalTests.cs @@ -46,6 +46,7 @@ public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl) [Test] [Arguments("/about?rid=abc", "https://essentialcsharp.com/about", "Learn about Essential C#")] [Arguments("/home", "https://essentialcsharp.com/home", "Explore Essential C#")] + [Arguments("/cookie-policy", "https://essentialcsharp.com/cookie-policy", "uses cookies")] [Arguments("/guidelines", "https://essentialcsharp.com/guidelines", "coding guidelines")] [Arguments("/announcements", "https://essentialcsharp.com/announcements", "announcements")] [Arguments("/TermsOfService", "https://essentialcsharp.com/TermsOfService", "terms of service")] @@ -54,35 +55,37 @@ public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl) [Arguments("/hello-world", "https://essentialcsharp.com/introducing-c", "Hello")] public async Task PagesHaveOneCanonicalAndPageSpecificDescriptions(string path, string expectedCanonical, string expectedDescription) { - using HttpResponseMessage response = await factory.CreateClient().GetAsync(path); + using HttpClient client = CreateClientWithoutAutoRedirect(); + using HttpResponseMessage response = await GetFollowingGetRedirectsAsync(client, path); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); HtmlDocument document = new(); document.LoadHtml(await response.Content.ReadAsStringAsync()); - HtmlNode head = document.DocumentNode.SelectSingleNode("//head"); - HtmlNodeCollection canonicals = head.SelectNodes("link[@rel='canonical']"); + HtmlNode head = document.DocumentNode.SelectSingleNode("//head") ?? throw new InvalidOperationException("Missing head element"); + HtmlNodeCollection canonicals = head.SelectNodes("link[@rel='canonical']") ?? throw new InvalidOperationException("Missing canonical link"); await Assert.That(canonicals.Count).IsEqualTo(1); await Assert.That(canonicals[0].GetAttributeValue("href", "")).IsEqualTo(expectedCanonical); - await Assert.That(head.SelectSingleNode("meta[@property='og:url']").GetAttributeValue("content", "")).IsEqualTo(expectedCanonical); + await Assert.That((head.SelectSingleNode("meta[@property='og:url']") ?? throw new InvalidOperationException("Missing OG URL")).GetAttributeValue("content", "")).IsEqualTo(expectedCanonical); - string description = head.SelectSingleNode("meta[@name='description']").GetAttributeValue("content", ""); + string description = (head.SelectSingleNode("meta[@name='description']") ?? throw new InvalidOperationException("Missing description")).GetAttributeValue("content", ""); await Assert.That(description).Contains(expectedDescription); - await Assert.That(head.SelectNodes("meta[@name='description']").Count).IsEqualTo(1); - await Assert.That(head.SelectSingleNode("meta[@property='og:description']").GetAttributeValue("content", "")).IsEqualTo(description); - await Assert.That(head.SelectSingleNode("meta[@name='twitter:description']").GetAttributeValue("content", "")).IsEqualTo(description); + await Assert.That((head.SelectNodes("meta[@name='description']") ?? throw new InvalidOperationException("Missing description")).Count).IsEqualTo(1); + await Assert.That((head.SelectSingleNode("meta[@property='og:description']") ?? throw new InvalidOperationException("Missing OG description")).GetAttributeValue("content", "")).IsEqualTo(description); + await Assert.That((head.SelectSingleNode("meta[@name='twitter:description']") ?? throw new InvalidOperationException("Missing Twitter description")).GetAttributeValue("content", "")).IsEqualTo(description); } [Test] public async Task NotFoundPageKeepsDescriptionFallbackWithoutCanonical() { - using HttpResponseMessage response = await factory.CreateClient().GetAsync("/non-existing-page1234"); + using HttpClient client = CreateClientWithoutAutoRedirect(); + using HttpResponseMessage response = await GetFollowingGetRedirectsAsync(client, "/non-existing-page1234"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); HtmlDocument document = new(); document.LoadHtml(await response.Content.ReadAsStringAsync()); - HtmlNode head = document.DocumentNode.SelectSingleNode("//head"); + HtmlNode head = document.DocumentNode.SelectSingleNode("//head") ?? throw new InvalidOperationException("Missing head element"); await Assert.That(head.SelectNodes("link[@rel='canonical']")).IsNull(); - await Assert.That(head.SelectSingleNode("meta[@name='description']").GetAttributeValue("content", "")) + await Assert.That((head.SelectSingleNode("meta[@name='description']") ?? throw new InvalidOperationException("Missing description")).GetAttributeValue("content", "")) .Contains("Accelerate your development knowledge"); } diff --git a/EssentialCSharp.Web/Controllers/HomeController.cs b/EssentialCSharp.Web/Controllers/HomeController.cs index fad3f3ef..c9ce94b7 100644 --- a/EssentialCSharp.Web/Controllers/HomeController.cs +++ b/EssentialCSharp.Web/Controllers/HomeController.cs @@ -78,6 +78,7 @@ public IActionResult TermsOfService() public IActionResult CookiePolicy() { ViewBag.PageTitle = "Cookie Policy"; + ViewData["Description"] = "Learn how Essential C# uses cookies and manages your privacy preferences."; return View(); } From 5a2f122a9deb054d0f42b5a1f4a76fcc272add3a Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Fri, 16 Oct 2026 18:58:34 -0700 Subject: [PATCH 3/3] fix(seo): emit one domain-aware canonical per page Re-base parser chapter canonicals onto SiteSettings:BaseUrl, keeping the primary page path for alias routes, and strip the parser canonical so the layout renders exactly one canonical/og:url. Pin BaseUrl in metadata tests and cover dev.essentialcsharp.com. Supersedes the request-Host approach from #1130 without enabling X-Forwarded-Host. --- EssentialCSharp.Web.Tests/FunctionalTests.cs | 26 ++++++++++++++++++- .../Controllers/HomeController.cs | 24 ++++++++++++----- .../Views/Shared/_Layout.cshtml | 2 +- README.md | 2 +- 4 files changed, 45 insertions(+), 9 deletions(-) diff --git a/EssentialCSharp.Web.Tests/FunctionalTests.cs b/EssentialCSharp.Web.Tests/FunctionalTests.cs index a3698e9d..32b785f9 100644 --- a/EssentialCSharp.Web.Tests/FunctionalTests.cs +++ b/EssentialCSharp.Web.Tests/FunctionalTests.cs @@ -1,5 +1,9 @@ using System.Net; using HtmlAgilityPack; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Hosting; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; namespace EssentialCSharp.Web.Tests; @@ -55,7 +59,27 @@ public async Task WhenPagesAreAccessed_TheyReturnHtml(string relativeUrl) [Arguments("/hello-world", "https://essentialcsharp.com/introducing-c", "Hello")] public async Task PagesHaveOneCanonicalAndPageSpecificDescriptions(string path, string expectedCanonical, string expectedDescription) { - using HttpClient client = CreateClientWithoutAutoRedirect(); + await using WebApplicationFactory factory = CreateFactoryWithBaseUrl("https://essentialcsharp.com"); + await AssertPageMetadata(factory, path, expectedCanonical, expectedDescription); + } + + [Test] + [Arguments("/about", "https://dev.essentialcsharp.com/about", "Learn about Essential C#")] + [Arguments("/introducing-c", "https://dev.essentialcsharp.com/introducing-c", "Introducing C#")] + [Arguments("/hello-world?rid=abc", "https://dev.essentialcsharp.com/introducing-c", "Hello")] + public async Task CanonicalUrlsUseConfiguredDeploymentOrigin(string path, string expectedCanonical, string expectedDescription) + { + await using WebApplicationFactory factory = CreateFactoryWithBaseUrl("https://dev.essentialcsharp.com/"); + await AssertPageMetadata(factory, path, expectedCanonical, expectedDescription); + } + + private WebApplicationFactory CreateFactoryWithBaseUrl(string baseUrl) => + Factory.Inner.WithWebHostBuilder(builder => builder.ConfigureServices(services => + services.PostConfigure(settings => settings.BaseUrl = baseUrl))); + + private static async Task AssertPageMetadata(WebApplicationFactory factory, string path, string expectedCanonical, string expectedDescription) + { + using HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); using HttpResponseMessage response = await GetFollowingGetRedirectsAsync(client, path); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); diff --git a/EssentialCSharp.Web/Controllers/HomeController.cs b/EssentialCSharp.Web/Controllers/HomeController.cs index c9ce94b7..1437d956 100644 --- a/EssentialCSharp.Web/Controllers/HomeController.cs +++ b/EssentialCSharp.Web/Controllers/HomeController.cs @@ -40,17 +40,29 @@ public IActionResult Index() styleNode.SetAttributeValue("nonce", nonce); } } + // The parser emits a canonical with a hardcoded production origin. Keep its path (so alias routes + // still point at the primary page) but re-base it on this deployment's configured origin, and + // remove it from the injected head so the layout renders exactly one canonical. + string canonicalPath = "/" + siteMapping.PrimaryKey; + foreach (HtmlNode canonicalNode in doc.DocumentNode.SelectNodes("/html/head/link[@rel='canonical']")?.ToList() ?? []) + { + string href = canonicalNode.GetAttributeValue("href", ""); + if (Uri.TryCreate(href, UriKind.Absolute, out Uri? absolute)) + { + canonicalPath = absolute.AbsolutePath; + } + else if (href.StartsWith('/')) + { + canonicalPath = href.Split('?', '#')[0]; + } + canonicalNode.Remove(); + } string headHtml = doc.DocumentNode.Element("html")?.Element("head")?.InnerHtml ?? string.Empty; string html = doc.DocumentNode.Element("html")?.Element("body")?.InnerHtml ?? string.Empty; - HtmlNode? canonical = doc.DocumentNode.SelectSingleNode("/html/head/link[@rel='canonical']"); ViewBag.PageTitle = siteMapping.IndentLevel is 0 ? siteMapping.ChapterTitle + " " + siteMapping.RawHeading : siteMapping.RawHeading; ViewData["Description"] = chapterDescriptionService.GetDescription(siteMapping); - if (canonical is not null) - { - ViewData["CanonicalUrl"] = canonical.GetAttributeValue("href", ""); - ViewData["HeadHasCanonical"] = true; - } + ViewData["CanonicalUrl"] = $"{siteSettings.Value.BaseUrl.TrimEnd('/')}{Request.PathBase}{canonicalPath}"; ViewBag.NextPage = FlipPage(siteMapping!.ChapterNumber, siteMapping.PageNumber, true); ViewBag.CurrentPageKey = siteMapping.PrimaryKey; ViewBag.PreviousPage = FlipPage(siteMapping.ChapterNumber, siteMapping.PageNumber, false); diff --git a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml index 3dc7b1c3..80b695d5 100644 --- a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml +++ b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml @@ -30,7 +30,7 @@ - @if (ViewData["HeadHasCanonical"] is not true && Context.Response.StatusCode < 400 && !Context.Request.Path.StartsWithSegments("/Identity")) + @if (Context.Response.StatusCode < 400 && !Context.Request.Path.StartsWithSegments("/Identity")) { } diff --git a/README.md b/README.md index 3ae4ddd4..da7c48b6 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,6 @@ For information on setting up your local development environment, please see the The shared layout uses `ViewData["Description"]` for the HTML, Open Graph, and Twitter descriptions; pages without an override use the site-wide fallback. Public page actions set their own descriptions. Chapter pages use `Chapters/sitemap.descriptions.json` when available (generated by ParserCli), or a description based on the chapter heading when the file is absent. Views can also set `ViewData["Description"]` before the layout renders. -Parser-generated chapter HTML supplies its canonical link; other public pages get a canonical link from the layout. Open Graph URLs follow the canonical URL, with `SiteSettings:BaseUrl` and the request path used when no chapter canonical is available. Query strings are excluded. +The layout renders exactly one canonical link (and a matching `og:url`) for every successful, non-Identity page. Its origin always comes from `SiteSettings:BaseUrl`, so each deployment must set it to its own origin (for example `SiteSettings__BaseUrl=https://dev.essentialcsharp.com` for the dev environment). The request `Host` header is deliberately not used, to avoid host-header poisoning. For chapter pages, the path from the parser-generated canonical is kept (so alias routes such as `/hello-world` point to the primary page) and re-based onto the configured origin; the parser's own `` is removed from the injected head. Other pages use the request path. Query strings are excluded. Please use issues or discussions to report issues found.