diff --git a/src/Microsoft.AspNetCore.Razor.Language/RazorSourceDocument.cs b/src/Microsoft.AspNetCore.Razor.Language/RazorSourceDocument.cs index ef0fabef5f..31acb7dfd6 100644 --- a/src/Microsoft.AspNetCore.Razor.Language/RazorSourceDocument.cs +++ b/src/Microsoft.AspNetCore.Razor.Language/RazorSourceDocument.cs @@ -196,7 +196,8 @@ namespace Microsoft.AspNetCore.Razor.Language using (var stream = projectItem.Read()) { // Autodetect the encoding. - return new StreamSourceDocument(stream, null, new RazorSourceDocumentProperties(filePath, projectItem.RelativePhysicalPath)); + var relativePath = projectItem.RelativePhysicalPath ?? projectItem.FilePath; + return new StreamSourceDocument(stream, null, new RazorSourceDocumentProperties(filePath, relativePath)); } } diff --git a/test/Microsoft.AspNetCore.Razor.Language.Test/RazorSourceDocumentTest.cs b/test/Microsoft.AspNetCore.Razor.Language.Test/RazorSourceDocumentTest.cs index fbae2747c2..9c05f2851c 100644 --- a/test/Microsoft.AspNetCore.Razor.Language.Test/RazorSourceDocumentTest.cs +++ b/test/Microsoft.AspNetCore.Razor.Language.Test/RazorSourceDocumentTest.cs @@ -93,7 +93,7 @@ namespace Microsoft.AspNetCore.Razor.Language // Assert Assert.Equal("c:\\myapp\\filePath.cshtml", document.FilePath); - Assert.Null(document.RelativePath); + Assert.Equal("filePath.cshtml", document.RelativePath); Assert.Equal(projectItem.Content, ReadContent(document)); } @@ -123,7 +123,7 @@ namespace Microsoft.AspNetCore.Razor.Language // Assert Assert.Equal("filePath.cshtml", document.FilePath); - Assert.Null(document.RelativePath); + Assert.Equal("filePath.cshtml", document.RelativePath); Assert.Equal(projectItem.Content, ReadContent(document)); } @@ -177,6 +177,37 @@ namespace Microsoft.AspNetCore.Razor.Language Assert.Same(Encoding.UTF32, Assert.IsType(document).Encoding); } + [Fact] + public void ReadFrom_WithProjectItem_FallbackToFilePath_WhenRelativePhysicalPathIsNull() + { + // Arrange + var filePath = "filePath.cshtml"; + var projectItem = new TestRazorProjectItem(filePath, relativePhysicalPath: null); + + // Act + var document = RazorSourceDocument.ReadFrom(projectItem); + + // Assert + Assert.Equal(filePath, document.FilePath); + Assert.Equal(filePath, document.RelativePath); + } + + [Fact] + public void ReadFrom_WithProjectItem_UsesRelativePhysicalPath() + { + // Arrange + var filePath = "filePath.cshtml"; + var relativePhysicalPath = "relative-path.cshtml"; + var projectItem = new TestRazorProjectItem(filePath, relativePhysicalPath: relativePhysicalPath); + + // Act + var document = RazorSourceDocument.ReadFrom(projectItem); + + // Assert + Assert.Equal(relativePhysicalPath, document.FilePath); + Assert.Equal(relativePhysicalPath, document.RelativePath); + } + private static string ReadContent(RazorSourceDocument razorSourceDocument) { var buffer = new char[razorSourceDocument.Length];