I need to run some analysis on the source code of a web application, including its views, using Roslyn.
Since it can only parse C# files and not razor views, I planned to convert the views into uncompiled .cs files and then have Roslyn parse that.
How can I do that?
Razor files with a . cshtml extension are compiled at both build and publish time using the Razor SDK. Runtime compilation may be optionally enabled by configuring the project.
A file with . cshtml extension is a C# HTML file that is used at server side by Razor Markup engine to render the webpage files to user's browser. This server side coding is similar to the standard ASP.NET page enabling dynamic web content creation on the fly as the webpage is written to the browser.
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML. Files containing Razor generally have a . cshtml file extension.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
I think the extension package Razor Generator is what you're looking for.
Generates source code from Razor files (.cshtml files), allowing them to be compiled into your assemblies. Supports MVC, Web Pages and standalone templates.
I am generating .cs
file from Razor .cshtml
files with help of Razor Generator library.
Generated cs
files contains line information from the .cshtml
source files. So if you run your Roslyn analyzer against .cs
files you can map the source line from .cs
file back to the original .cshtml
file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With