1

To write the integration tests more easily, I've put the controllers in another project than the host (the one with the startup). This project has the following files:

|
|-- Controllers
|   +-- HomeController.cs
|
+-- Views
    +-- Home
        +-- Index.cshtml

My startup can find the controller thanks to this solution:

services.AddMvc().AddApplicationPart(typeof(HomeController).Assembly);

However, I didn't find any way to set the path of the views. It seems to be relative to the startup place, and not the controller: when I run the application, I get that error:

InvalidOperationException: The view 'Index' was not found. The following locations were searched:
/Views/Home/Index.cshtml
/Views/Shared/Index.cshtml
/Pages/Shared/Index.cshtml

How to specify that the views are in the same folder that the controllers?

Boiethios
  • 38,438
  • 19
  • 134
  • 183
  • I've tried this solution, and it did not work: https://www.jackhiston.com/2017/8/15/sharing-controllers-and-views-in-aspnet-core/ – Boiethios Aug 30 '19 at 16:36
  • I'm not that familiar with Asp.Net Core, but in .Net Framework MVC, you would implement a custom `IViewEngine`. –  Aug 30 '19 at 19:01
  • @FrenchBoiethios 1. I tried the [solution](https://www.jackhiston.com/2017/8/15/sharing-controllers-and-views-in-aspnet-core/) you mentioned above, it works fine for me. Did you add the `` within the library? 2. Apart from that solution, a much easier way is to change your controllers & views project to be **[Razor component Library, RCL]**, and then simply add a reference to the RCL, in this case, there's no need to `AddApplicationPart()` as well as `Configure` – itminus Sep 02 '19 at 04:50
  • @itminus 1. I'm stupid, I did add the `` tag in the host project. It works when I put it inside the library project 2. This solution is indeed the best one. Since you solved my issue, can you write an answer? – Boiethios Sep 02 '19 at 07:24

1 Answers1

2
  1. I tried the solution you mentioned above, it works fine for me. Did you add the <EmbeddedResource ...> within the library?

  2. Apart from that solution, a much easier way is to change your controllers & views project to be a Razor component Library, RCL:

<Project Sdk="Microsoft.NET.Sdk.Razor">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="2.2.0" />
  </ItemGroup>
</Project>

and then simply add a reference to the RCL, in this case, there's no need to AddApplicationPart() as well as .Configure<RazorViewEngineOptions>()

itminus
  • 23,772
  • 2
  • 53
  • 88
  • 1
    The reference to `Microsoft.AspNetCore.Mvc` was marked as private in my csproj, so I had to remove the `PrivateAssets="All"` for this solution to work. – Boiethios Sep 02 '19 at 07:32
  • @FrenchBoiethios I update the demo `*.csproj` of RCL for reference :) – itminus Sep 02 '19 at 07:36