Razor class Library is a new feature of ASP. NET Core 2.1, you can compile the MVC view into an assembly for other project references, see CREATE reusable UI using the Razor class library PR Oject in ASP-Core
Previously we implemented a common class library in the form of "Middleware + string Stitching page HTML" in order to achieve common custom error pages in various projects, but it was very complicated and inconvenient to maintain the page.
The Razor Class Library is the right solution to our pain and experience this new feature in the heat of today's. NET Core 2.1 release.
Modify directly in the existing class library project, first in the. csproj <project Sdk= "MICROSOFT.NET.SDK"> Change to <Project Sdk= "Microsoft.NET.Sdk.Razor"> , and NuGet installs MICROSOFT.ASPNETCORE.MVC .
Then create the Pages/errors folder and add 400.cshtml, 404.cshtml, 500.cshtml of these 3 Razor Page files.
If you add another Web project to the solution, referencing the RCL class library project, you can access the custom error page directly through a path such as/error/404, and the view encapsulated in the class library is in effect.
Enabling these custom error pages requires the following code to be added to the Startup Configure method:
App. Useexceptionhandler ("/errors/500"); app. Usestatuscodepageswithreexecute ("/errors/{0}");
For ease of use, implement an extension method:
public static class customerrorpagesextensions{ Public static iapplicationbuilder usecustomerrorpages (this Iapplicationbuilder app) {app. Useexceptionhandler ( /errors/500 ); App. Usestatuscodepageswithreexecute ( / errors/{0} ); return app; }}
Then publish the NuGet package, use the project to install the NuGet package, and add the app to the Startup Configure. Usecustomerrorpages ().
Public void Configure (Iapplicationbuilder app, Ihostingenvironment env) { if (env. Isdevelopment ()) { app. Usedeveloperexceptionpage (); } Else { app. Usecustomerrorpages (); }}
The Razor Class Library is not only easy to maintain in the future, but also super simple and refreshing, marvel at the RCL and throw all the previous code into the Trash.
Common class library for implementing custom error pages for the Razor class library based on ASP. NET Core 2.1