Search code examples
c#asp.net-mvcasp.net-corerazor

Check if project file exists in ASP.NET Core


I'm working on an ASP.NET Core webapp and it's common to render .cshtml files by using code like this (if you are new to ASP.NET Core please notice a .cshtml file is HTML code with embed C# code under the '@' prefix). The most common code when rendering a .csthml view on any section of the web is like this, and the path is always a file of our Visual Studio 2022 solution:

<body>
    <partial>
        @await Html.PartialAsync("~/Views/Shared/Forms/_ContactForm.cshtml")
    </partial>
</body>

Our main problem is that .cshtml files are frequently renamed, or moved to another sub-directory since the project is growing, and then all references to a path fails and we have no notice until a user run and check the corresponding sub-page of the website.

I'm sure the problem is independent of using ASP.NET Core or another framework, so any general solution could fit here: ¿How can we ensure we get a COMPILER error when a project file path doesn't exists anymore? ¿any other idea based on our particular case? Most of issues are derived from this file paths and it's really annoying.


Solution

  • How can we ensure we get a COMPILER error when a project file path doesn't exists anymore

    It can be quite cumbersome. AFAIK some IDEs like ReSharper/Rider try to implement similar checks but even theirs attempts far from perfect (at least in my experience I have seen a lot of false positives for example). But you can always look into writing into your own Roslyn analyzer which will take into account the project structure.

    any other idea based on our particular case

    I would argue that easier and more robust in general approach would to use infrastructure provided by ASP.NET Core for integration tests and just write tests which will ensure that corresponding pages at least return success status code. Example from docs:

    public class BasicTests 
        : IClassFixture<WebApplicationFactory<Program>>
    {
        private readonly WebApplicationFactory<Program> _factory;
    
        public BasicTests(WebApplicationFactory<Program> factory)
        {
            _factory = factory;
        }
    
        [Theory]
        [InlineData("/")]
        [InlineData("/Index")]
        [InlineData("/About")]
        [InlineData("/Privacy")]
        [InlineData("/Contact")]
        public async Task Get_EndpointsReturnSuccessAndCorrectContentType(string url)
        {
            // Arrange
            var client = _factory.CreateClient();
    
            // Act
            var response = await client.GetAsync(url);
    
            // Assert
            response.EnsureSuccessStatusCode(); // Status Code 200-299
            Assert.Equal("text/html; charset=utf-8", 
                response.Content.Headers.ContentType.ToString());
        }
    }