We could share controllers, views, Razor Pages and more with Application Parts.
Application Parts allow ASP.NET Core to discover controllers, view components, tag helpers, Razor Pages, razor compilation sources, and more. AssemblyPart is an Application part. AssemblyPart encapsulates an assembly reference and exposes types and compilation references.
You could refer the following steps to use Application Parts.
Create a ClassLibray (.net core) named "MySharedApp", and add the following package via NuGet.
- Microsoft.Extensions.FileProviders.Embedded
- Microsoft.AspNetCore.Mvc
Add the Controller and Views with the following folder structure:
MySharedController.cs:
//Require using Microsoft.AspNetCore.Mvc;
public class MySharedController : Controller
{
public IActionResult Index()
{
return Ok("Message from shared assembly!");
}
public IActionResult IndexView()
{
return View("Index");
}
}
Index.cshtml:
<h1>
Message from shared assembly!
</h1>
<h2> Using a View</h2>
[Note] For the view pages, right click it and open the Properties panel, set the Build Action as "Embedded resource" (it can prevent the view page not found issue in the Main web app).
Build the ClassLibrary.
In the same solution, create a new Asp.net Core Web Application (MVC application).
Right click the Dependencies, select "Add Project Reference...", select the MySharedApp ClassLibary, then click OK to add the reference.
You could also click the Dependencies, select "Add Project Reference...", then, in the Browser tab, Click the "Browser" button and select the MySharedApp.dll, then click OK to add the reference.
After that, the Dependencies looks as below:
In the MVC application Startup.ConfigureServices method, use the following code to discover and load the controller and view.
public void ConfigureServices(IServiceCollection services)
{
// services.AddControllersWithViews();
#region
// Requires MySharedApp.Controllers;
// Requires using Microsoft.AspNetCore.Mvc.Razor.RuntimeCompilation;
// Requires using Microsoft.Extensions.FileProviders;
var assembly = typeof(MySharedController).Assembly;
services.AddControllersWithViews()
.AddApplicationPart(assembly)
.AddRazorRuntimeCompilation();
services.Configure<MvcRazorRuntimeCompilationOptions>(options =>
{ options.FileProviders.Add(new EmbeddedFileProvider(assembly)); });
#endregion
}
After that, add the hyperlink to navigate the controller and view:
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="MyShared" asp-action="Index">MyShared</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="MyShared" asp-action="IndexView">MyShared View</a>
</li>
The test screenshot as below:
More detail information about using Application Parts, check Share controllers, views, Razor Pages and more with Application Parts
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…