ASP.NET load views from another assembly

Viewed 219

I have a C# Solution containing two projects : Client (parent) and RestAPI (child). From the client project, I'm loading a ASP.NET server. Currently, my RestAPI is successfully loading controllers from the client project using services.AddControllersWithViews().AddApplicationPart(assembly);. Currently, only the controllers can be loaded, though, I want to use some views too.

To summarize, what I'm trying to do is to use views that are located into my Client project by the RestAPI project.

What I've tried to do :

  1. services.AddControllersWithViews().AddApplicationPart(assembly); => It loads only the controllers
  2. services.AddMvc().AddApplicationPart(assembly); => Same results
  3. Returning a static path to the view file (i.e. : return View("C:\Simon\...");)

Project structure :

enter image description here

In the controller DevicesController.cs, I have to following function:

[Route("show")]
[HttpGet]
public ViewResult Show()
{
return View("Home");
}

I want to return the view in the Views folder located under Client project. However, It only returns the one located under RestAPI. If I remove the one in RestAPI, the application crashes with the following error logs :

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

1 Answers

I think you have to consider adding relatedAssemblies.

private static void AddApplicationPart(IMvcBuilder mvcBuilder, Assembly assembly)
    {
        var partFactory = ApplicationPartFactory.GetApplicationPartFactory(assembly);
        foreach (var part in partFactory.GetApplicationParts(assembly))
        {
            mvcBuilder.PartManager.ApplicationParts.Add(part);
        }

        var relatedAssemblies = RelatedAssemblyAttribute.GetRelatedAssemblies(assembly, throwOnError: false);
        foreach (var relatedAssembly in relatedAssemblies)
        {
            partFactory = ApplicationPartFactory.GetApplicationPartFactory(relatedAssembly);
            foreach (var part in partFactory.GetApplicationParts(relatedAssembly))
            {
                mvcBuilder.PartManager.ApplicationParts.Add(part);
            }
        }
    }
Related