Sponsor: Do you build complex software systems? See how NServiceBus makes it easier to design, build, and manage software systems that use message queues to achieve loose coupling. Get started for free.
I ran into a situation where I wanted to use a Razor views and layouts that were in a .NET Standard 2.0 class library from my ASP.NET Core MVC Project. There were two issues that I ran into that I will cover in this post. First is actually getting the MVC project to recognize the views in the class library. Second was having Rider or Resharper in Visual Studio, understand where the views were located.Microsoft.NET.Sdk.Razor
In .NET Core 2.1 SDK (or presumably later) there is now a Microsoft.NET.Sdk.Razor MSBuild SDK.In my .NET Standard class library, this means modifying the SDK property to reference
- Standardizes the experience around building, packaging, and publishing projects containing Razor files for ASP.NET Core MVC-based projects.
- Includes a set of predefined targets, properties, and items that allow customizing the compilation of Razor files.
Microsoft.NET.Sdk.Razor
instead of Microsoft.NET.Sdk
Now if I reference this project from my MVC project, I can use any views located in that class library.
Here’s an outline of my sample solution that shows the project structure.
Now in my DemoControler.cs
, I’m using the model and view from the ClassLibrary
project.
JetBrains Rider / Resharper
Although this works and the views are located and process correctly at runtime, Visual Studio + ReShaper or JetBrains Rider will complain about now being able to locate the view. Thankfully, Maarten Balliauw helped me out and provided the solution. First, you need to add aPackageReference
to the NuGet Package JetBrains.Annotations in our MVC project.
Then we can use the AspMvcViewLocationFormat
attribute to tell Reshaper/Rider where our views are located. You can put this attribute anywhere. I just put in my Startup.cs
At this point ReSharper/Rider will understand where the views are and no longer provide any errors.