1. 程式人生 > >將終結點圖新增到你的ASP.NET Core應用程式中

將終結點圖新增到你的ASP.NET Core應用程式中

在本文中,我將展示如何使用`DfaGraphWriter`服務在ASP.NET Core 3.0應用程式中視覺化你的終結點路由。上面文章我向您演示瞭如何生成一個有向圖([如我上篇文章中所示](https://www.cnblogs.com/yilezhu/p/13301981.html)),可以使用[GraphVizOnline](https://dreampuf.github.io/GraphvizOnline/)將其視覺化。最後,我描述了應用程式生命週期中可以檢索圖形資料的點。 > 作者:依樂祝 > > 原文地址:https://www.cnblogs.com/yilezhu/p/13335749.html > > 譯文地址:https://andrewlock.net/adding-an-endpoint-graph-to-your-aspnetcore-application/ 在本文中,我僅展示如何建立圖形的“預設”樣式。在我的下一批那文章中,我再建立一個自定義的`writer`來生成自定義的圖[如上篇文章所示](https://www.cnblogs.com/yilezhu/p/13301981.html)。 ## 使用`DfaGraphWriter`視覺化您的終結點 ASP.NET Core附帶了[一個方便的類`DfaGraphWriter`](https://github.com/dotnet/aspnetcore/blob/36856ca8f9932b88757bbf24904bf36868b4d727/src/Http/Routing/src/Internal/DfaGraphWriter.cs)可用於視覺化ASP.NET Core 3.x應用程式中的終結點路由: ```csharp public class DfaGraphWriter { public void Write(EndpointDataSource dataSource, TextWriter writer); } ``` 此類只有一個方法`Write`。`EndpointDataSource`包含描述您的應用程式的`Endpoint`集合,`TextWriter`用於編寫DOT語言圖([如您在前一篇文章中所見](https://www.cnblogs.com/yilezhu/p/13301981.html))。 現在,我們將建立一箇中間件,該中介軟體使用`DfaGraphWriter`將該圖編寫為HTTP響應。您可以使用DI 將`DfaGraphWriter`和`EndpointDataSource`注入到建構函式中: ```csharp public class GraphEndpointMiddleware { // inject required services using DI private readonly DfaGraphWriter _graphWriter; private readonly EndpointDataSource _endpointData; public GraphEndpointMiddleware( RequestDelegate next, DfaGraphWriter graphWriter, EndpointDataSource endpointData) { _graphWriter = graphWriter; _endpointData = endpointData; } public async Task Invoke(HttpContext context) { // set the response context.Response.StatusCode = 200; context.Response.ContentType = "text/plain"; // Write the response into memory await using (var sw = new StringWriter()) { // Write the graph _graphWriter.Write(_endpointData, sw); var graph = sw.ToString(); // Write the graph to the response await context.Response.WriteAsync(graph); } } } ``` 這個中介軟體非常簡單-我們使用依賴注入將必要的服務注入到中介軟體中。將圖形寫入響應有點複雜:您必須在記憶體中將響應寫到一個 `StringWriter`,再將其轉換為 `string`,*然後*將其寫到圖形。 這一切都是必要的,因為`DfaGraphWriter`寫入`TextWriter`使用*同步* `Stream` API呼叫,如`Write`,而不是`WriteAsync`。如果有非同步方法,理想情況下,我們將能夠執行以下操作: ```csharp // Create a stream writer that wraps the body await using (var sw = new StreamWriter(context.Response.Body)) { // write asynchronously to the stream await _graphWriter.WriteAsync(_endpointData, sw); } ``` 如果`DfaGraphWriter`使用了非同步API,則可以如上所述直接寫入`Response.Body`,而避免使用in-memory `string`。不幸的是,它是同步的,[出於效能原因您不應該使用同步呼叫直接寫入`Response.Body`](https://docs.microsoft.com/en-us/aspnet/core/performance/performance-best-practices?view=aspnetcore-3.1#avoid-synchronous-read-or-write-on-httprequesthttpresponse-body)。如果您*嘗試*使用上面的模式,則*可能會*得到如下所示內容的`InvalidOperationException`異常,具體取決於所寫圖形的大小: ```bash System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead. ``` > 如果圖形很小,則可能**不會出現**此異常,但是如果您嘗試對映中等規模的應用程式(例如帶有Identity的預設Razor Pages應用程式),則可以看到此異常。 讓我們回到正軌上-我們現在有了一個圖形生成中介軟體,所以讓我們把它新增到管道中。這裡有兩個選擇: - 使用終結點路由將其新增為終結點。 - 從中介軟體管道中將其新增為簡單的“分支”。 通常建議使用前一種方法,將終結點新增到ASP.NET Core 3.0應用程式,因此從這裡開始。 ### 將圖形視覺化器新增為終結點 為了簡化終結點註冊程式碼,我將建立一個簡單的擴充套件方法以將`GraphEndpointMiddleware`作為終結點新增: ```csharp public static class GraphEndpointMiddlewareExtensions { public static IEndpointConventionBuilder MapGraphVisualisation( this IEndpointRouteBuilder endpoints, string pattern) { var pipeline = endpoints .CreateApplicationBuilder() .UseMiddleware() .Build(); return endpoints.Map(pattern, pipeline).WithDisplayName("Endpoint Graph"); } } ``` 然後,我們可以在`Startup.Configure()`中的`UseEndpoints()`方法中呼叫`MapGraphVisualisation("/graph")`將圖形終結點新增到我們的ASP.NET Core應用程式中: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/healthz"); endpoints.MapControllers(); // Add the graph endpoint endpoints.MapGraphVisualisation("/graph"); }); } ``` 這就是我們要做的。該`DfaGraphWriter`已經在DI中可用,因此不需要額外的配置。導航至`http://localhost:5000/graph`將以純文字形式生成我們的終結點圖: ```javascript digraph DFA { 0 [label="/graph/"] 1 [label="/healthz/"] 2 [label="/api/Values/{...}/ HTTP: GET"] 3 [label="/api/Values/{...}/ HTTP: PUT"] 4 [label="/api/Values/{...}/ HTTP: DELETE"] 5 [label="/api/Values/{...}/ HTTP: *"] 6 -> 2 [label="HTTP: GET"] 6 -> 3 [label="HTTP: PUT"] 6 -> 4 [label="HTTP: DELETE"] 6 -> 5 [label="HTTP: *"] 6 [label="/api/Values/{...}/"] 7 [label="/api/Values/ HTTP: GET"] 8 [label="/api/Values/ HTTP: POST"] 9 [label="/api/Values/ HTTP: *"] 10 -> 6 [label="/*"] 10 -> 7 [label="HTTP: GET"] 10 -> 8 [label="HTTP: POST"] 10 -> 9 [label="HTTP: *"] 10 [label="/api/Values/"] 11 -> 10 [label="/Values"] 11 [label="/api/"] 12 -> 0 [label="/graph"] 12 -> 1 [label="/healthz"] 12 -> 11 [label="/api"] 12 [label="/"] } ``` 我們可以使用`GraphVizOnline`進行視覺化顯示如下: ![一個ValuesController終結點路由應用程式](https://img2020.cnblogs.com/blog/1377250/202007/1377250-20200718144355087-1059378641.png) 在終結點路由系統中將圖形公開為終結點具有如下優點和缺點: - 您可以輕鬆地向終結點新增授權。您可能不希望任何人都能檢視此資料! - 圖形終結點顯示為系統中的終結點。這顯然是正確的,但可能會很煩人。 如果最後一點對您來說很重要,那麼您*可以*使用傳統的方法來建立終結點,即使用分支中介軟體。 ### 將圖形視覺化工具新增為中介軟體分支 在您進行終結點路由之前,將分支新增到中介軟體管道是建立“終結點”的最簡單方法之一。它在ASP.NET Core 3.0中仍然可用,它比終結點路由系統要更為,但不能輕鬆新增授權或高階路由。 要建立中介軟體分支,請使用`Map()`命令。例如,您可以使用以下命令新增分支: ```csharp public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // add the graph endpoint as a branch of the pipeline app.Map("/graph", branch => branch.UseMiddleware()); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapHealthChecks("/healthz"); endpoints.MapControllers(); }); } ``` 使用此方法的優缺點在本質上與終結點路由版本相反:圖形中沒有`/graph`終結點,您無法輕鬆地將授權應用於此終結點! ![沒有圖形終結點的ValuesController終結點路由應用程式](https://img2020.cnblogs.com/blog/1377250/202007/1377250-20200718144354777-1565399704.png) 對我來說,像這樣公開應用程式的圖形是沒有意義的。在下一節中,我將展示如何通過小型整合測試來生成圖形。 ## 從整合測試生成終結點圖 [ASP.NET Core對於執行記憶體整合測試有很好的設計](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests),它可以在不需要進行網路呼叫的情況下執行完整的中介軟體管道和API控制器/Razor頁面。 除了可以用來確認應用程式整體正確執行的傳統“端到端”整合測試之外,我有時還喜歡編寫“健全性檢查”測試,以確認應用程式配置正確。您可以使用,在*Microsoft.AspNetCore.Mvc.Testing*中暴露的底層DI容器中的[`WebApplicationFactory<>`設施](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1#basic-tests-with-the-default-webapplicationfactory)實現。這樣,您就可以在應用程式的DI上下文中執行程式碼,而無需通過單元測試。 現在,讓我們來試下吧 - 使用VS或`dotnet new xunit`來執行一個新的xUnit專案(我選擇的測試框架) - 通過執行`dotnet add package Microsoft.AspNetCore.Mvc.Testing`安裝*Microsoft.AspNetCore.Mvc.Testing* - 將測試專案的``元素更新為`` - 從測試專案中引用您的ASP.NET Core專案 現在,我們可以建立一個簡單的測試來生成終結點圖,並將其寫入測試輸出。在下面的示例中,我將預設值`WebApplicationFactory<>`作為類基礎設施;如果您需要自定義工廠,請參閱[文件](https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests#customize-webapplicationfactory)以獲取詳細資訊。 除了`WebApplicationFactory<>`,我還注入了`ITestOutputHelper`。您需要使用此類來記錄xUnit的測試輸出。[直接寫`Console`不會起作用。](https://xunit.net/docs/capturing-output)。 ```csharp public class GenerateGraphTest : IClassFixture { // Inject the factory and the output helper private readonly WebApplicationFactory _factory; private readonly ITestOutputHelper _output; public GenerateGraphTest( WebApplicationFactory factory, ITestOutputHelper output) { _factory = factory; _output = output; } [Fact] public void GenerateGraph() { // fetch the required services from the root container of the app var graphWriter = _factory.Services.GetRequiredService(); var endpointData = _factory.Services.GetRequiredService(); // build the graph as before using (var sw = new StringWriter()) { graphWriter.Write(endpointData, sw); var graph = sw.ToString(); // write the graph to the test output _output.WriteLine(graph); } } } ``` 測試的大部分內容與中介軟體相同,但是我們沒有編寫響應,而是編寫了xUnit的`ITestOutputHelper`以將記錄測試的結果輸出。在Visual Studio中,您可以通過以下方式檢視此輸出:開啟“測試資源管理器”,導航到`GenerateGraph`測試,然後單擊“為此結果開啟其他輸出”,這將以選項卡的形式開啟結果: ![在Visual Studio中檢視測試中的終結點資料](https://img2020.cnblogs.com/blog/1377250/202007/1377250-20200718144354153-1297063739.png) 我發現像這樣的簡單測試通常足以滿足我的目的。在我看來有如下這些優點: - 它不會將此資料公開為終結點 - 對您的應用沒有影響 - 容易產生 不過,也許您想從應用程式中生成此圖,但是您不想使用到目前為止顯示的任何一種中介軟體方法將其包括在內。如果是這樣,請務必小心在哪裡進行。 ## 您無法在`IHostedService`中生成圖形 一般而言,您可以在應用程式中任何使用依賴項注入或有權訪問例項的任何位置通過`IServiceProvider`訪問`DfaGraphWriter`和`EndpointDataSource`服務。這意味著在請求的上下文中(例如從MVC控制器或Razor Page生成)圖很容易,並且與您到目前為止所看到的方法相同。 如果您要嘗試在應用程式生命週期的*早期*生成圖形,則必須小心。尤其是`IHostedService`。 在ASP.NET Core 3.0中,Web基礎結構是在通用主機的基礎上重建的,這意味著您的伺服器(Kestrel)作為一個`IHostedService`在你的應用程式中執行的。在大多數情況下,這不會產生太大影響,但是與ASP.NET Core 2.x相比,它改變了應用程式的生成*順序*。 在ASP.NET Core 2.x中,將發生以下情況: - 中介軟體管道已建立。 - 伺服器(Kestrel)開始偵聽請求。 - 在`IHostedService`實現啟動。 而是在ASP.NET Core 3.x上,如下所示: - `IHostedService`實現啟動。 - ``` GenericWebHostService ``` 啟動: - 中介軟體管道已建立 - 伺服器(Kestrel)開始偵聽請求。 需要注意的重要一點是,直到您的`IHostedService`s的執行後中介軟體管道才會建立。由於`UseEndpoints()`尚未被呼叫,`EndpointDataSource`將不包含任何資料! > 如果您嘗試從一個`IHostedService`中的`DfaGraphWriter`生成圖表,該`EndpointDataSource`是空的。 如果嘗試使用其他標準機制來注入早期行為,情況也是如此,如`IStartupFilter`- `Startup.Configure()`執行*之前* 呼叫 ,因此`EndpointDataSource`將為空。 同樣,您不能只是在`Program.Main`呼叫`IHostBuilder.Build()`來構建一個`Host`,然後使用`IHost.Services`:來訪問服務,直到您呼叫`IHost.Run`,並且伺服器已啟動,否則您的終結點列表將為空! 這些限制可能不是問題,具體取決於您要實現的目標。對我來說,單元測試方法可以解決我的大多數問題。 無論使用哪種方法,都只能生成本文中顯示的“預設”終結點圖。這隱藏了很多真正有用的資訊,例如哪些節點生成了終結點。在下一篇文章中,我將展示如何建立自定義圖形編寫器,以便您可以生成自己的圖形。 ## 總結 在這篇文章中,我展示瞭如何使用`DfaGraphWriter`和`EndpointDataSource`建立應用程式中所有終結點的圖形。我展示瞭如何建立中介軟體終結點來公開此資料,以及如何將這種中介軟體與分支中介軟體策略一起用作終結點路由。 我還展示瞭如何使用簡單的整合測試來生成圖形資料而無需執行您的應用程式。這避免了公開(可能敏感)的終結點圖,同時仍然允許輕鬆訪問資料。 最後,我討論了*何時*可以在應用程式的生命週期中生成圖形。該`EndpointDataSource`未填充,直到後`Server`(Kestrel)已經開始,所以你主要限於在請求上下文訪問資料。`IHostedService`和`IStartupFilter`執行得太早以至於無法訪問資料,`IHostBuilder.Build()`只是構建DI容器,而沒有構建中介軟體