Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert razor .cshtml files to C# .cs files

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?

like image 616
Thomas Bonini Avatar asked Sep 16 '13 10:09

Thomas Bonini


People also ask

Do Cshtml files get compiled?

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.

What is Cshtml CS file?

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.

What is Razor C#?

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.

Is Razor better than MVC?

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.


2 Answers

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.

like image 178
spender Avatar answered Oct 08 '22 10:10

spender


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.

like image 33
opis-kladno Avatar answered Oct 08 '22 10:10

opis-kladno