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

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

在本文中,我將展示如何使用DfaGraphWriter服務在ASP.NET Core 3.0應用程式中視覺化你的終結點路由。上面文章我向您演示瞭如何生成一個有向圖(如我上篇文章中所示),可以使用GraphVizOnline將其視覺化。最後,我描述了應用程式生命週期中可以檢索圖形資料的點。

作者:依樂祝

原文地址:https://www.cnblogs.com/yilezhu/p/13335749.html

譯文地址:https://andrewlock.net/adding-an-endpoint-graph-to-your-aspnetcore-application/

在本文中,我僅展示如何建立圖形的“預設”樣式。在我的下一批那文章中,我再建立一個自定義的writer

來生成自定義的圖如上篇文章所示

使用DfaGraphWriter視覺化您的終結點

ASP.NET Core附帶了一個方便的類DfaGraphWriter可用於視覺化ASP.NET Core 3.x應用程式中的終結點路由:

public class DfaGraphWriter
{
public void Write(EndpointDataSource dataSource, TextWriter writer);
}

此類只有一個方法WriteEndpointDataSource包含描述您的應用程式的Endpoint集合,TextWriter用於編寫DOT語言圖(如您在前一篇文章中所見

)。

現在,我們將建立一箇中介軟體,該中介軟體使用DfaGraphWriter將該圖編寫為HTTP響應。您可以使用DI 將DfaGraphWriterEndpointDataSource注入到建構函式中:

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。如果有非同步方法,理想情況下,我們將能夠執行以下操作:

// 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。如果您嘗試使用上面的模式,則可能會得到如下所示內容的InvalidOperationException異常,具體取決於所寫圖形的大小:

System.InvalidOperationException: Synchronous operations are disallowed. Call WriteAsync or set AllowSynchronousIO to true instead.

如果圖形很小,則可能不會出現此異常,但是如果您嘗試對映中等規模的應用程式(例如帶有Identity的預設Razor Pages應用程式),則可以看到此異常。

讓我們回到正軌上-我們現在有了一個圖形生成中介軟體,所以讓我們把它新增到管道中。這裡有兩個選擇:

  • 使用終結點路由將其新增為終結點。
  • 從中介軟體管道中將其新增為簡單的“分支”。

通常建議使用前一種方法,將終結點新增到ASP.NET Core 3.0應用程式,因此從這裡開始。

將圖形視覺化器新增為終結點

為了簡化終結點註冊程式碼,我將建立一個簡單的擴充套件方法以將GraphEndpointMiddleware作為終結點新增:

public static class GraphEndpointMiddlewareExtensions
{
public static IEndpointConventionBuilder MapGraphVisualisation(
this IEndpointRouteBuilder endpoints, string pattern)
{
var pipeline = endpoints
.CreateApplicationBuilder()
.UseMiddleware<GraphEndpointMiddleware>()
.Build(); return endpoints.Map(pattern, pipeline).WithDisplayName("Endpoint Graph");
}
}

然後,我們可以在Startup.Configure()中的UseEndpoints()方法中呼叫MapGraphVisualisation("/graph")將圖形終結點新增到我們的ASP.NET Core應用程式中:

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將以純文字形式生成我們的終結點圖:

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進行視覺化顯示如下:

在終結點路由系統中將圖形公開為終結點具有如下優點和缺點:

  • 您可以輕鬆地向終結點新增授權。您可能不希望任何人都能檢視此資料!
  • 圖形終結點顯示為系統中的終結點。這顯然是正確的,但可能會很煩人。

如果最後一點對您來說很重要,那麼您可以使用傳統的方法來建立終結點,即使用分支中介軟體。

將圖形視覺化工具新增為中介軟體分支

在您進行終結點路由之前,將分支新增到中介軟體管道是建立“終結點”的最簡單方法之一。它在ASP.NET Core 3.0中仍然可用,它比終結點路由系統要更為,但不能輕鬆新增授權或高階路由。

要建立中介軟體分支,請使用Map()命令。例如,您可以使用以下命令新增分支:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
// add the graph endpoint as a branch of the pipeline
app.Map("/graph", branch =>
branch.UseMiddleware<GraphEndpointMiddleware>()); app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapHealthChecks("/healthz");
endpoints.MapControllers();
});
}

使用此方法的優缺點在本質上與終結點路由版本相反:圖形中沒有/graph終結點,您無法輕鬆地將授權應用於此終結點!

對我來說,像這樣公開應用程式的圖形是沒有意義的。在下一節中,我將展示如何通過小型整合測試來生成圖形。

從整合測試生成終結點圖

ASP.NET Core對於執行記憶體整合測試有很好的設計,它可以在不需要進行網路呼叫的情況下執行完整的中介軟體管道和API控制器/Razor頁面。

除了可以用來確認應用程式整體正確執行的傳統“端到端”整合測試之外,我有時還喜歡編寫“健全性檢查”測試,以確認應用程式配置正確。您可以使用,在Microsoft.AspNetCore.Mvc.Testing中暴露的底層DI容器中的WebApplicationFactory<>設施實現。這樣,您就可以在應用程式的DI上下文中執行程式碼,而無需通過單元測試。

現在,讓我們來試下吧

  • 使用VS或dotnet new xunit來執行一個新的xUnit專案(我選擇的測試框架)
  • 通過執行dotnet add package Microsoft.AspNetCore.Mvc.Testing安裝Microsoft.AspNetCore.Mvc.Testing
  • 將測試專案的<Project>元素更新為<Project Sdk="Microsoft.NET.Sdk.Web">
  • 從測試專案中引用您的ASP.NET Core專案

現在,我們可以建立一個簡單的測試來生成終結點圖,並將其寫入測試輸出。在下面的示例中,我將預設值WebApplicationFactory<>作為類基礎設施;如果您需要自定義工廠,請參閱檔案以獲取詳細資訊。

除了WebApplicationFactory<>,我還注入了ITestOutputHelper。您需要使用此類來記錄xUnit的測試輸出。直接寫Console不會起作用。

public class GenerateGraphTest
: IClassFixture<WebApplicationFactory<ApiRoutes.Startup>>
{ // Inject the factory and the output helper
private readonly WebApplicationFactory<ApiRoutes.Startup> _factory;
private readonly ITestOutputHelper _output; public GenerateGraphTest(
WebApplicationFactory<Startup> 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<DfaGraphWriter>();
var endpointData = _factory.Services.GetRequiredService<EndpointDataSource>(); // 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測試,然後單擊“為此結果開啟其他輸出”,這將以選項卡的形式開啟結果:

我發現像這樣的簡單測試通常足以滿足我的目的。在我看來有如下這些優點:

  • 它不會將此資料公開為終結點
  • 對您的應用沒有影響
  • 容易產生

不過,也許您想從應用程式中生成此圖,但是您不想使用到目前為止顯示的任何一種中介軟體方法將其包括在內。如果是這樣,請務必小心在哪裡進行。

您無法在IHostedService中生成圖形

一般而言,您可以在應用程式中任何使用依賴項注入或有權訪問例項的任何位置通過IServiceProvider訪問DfaGraphWriterEndpointDataSource服務。這意味著在請求的上下文中(例如從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)開始偵聽請求。

需要注意的重要一點是,直到您的IHostedServices的執行後中介軟體管道才會建立。由於UseEndpoints()尚未被呼叫,EndpointDataSource將不包含任何資料!

如果您嘗試從一個IHostedService中的DfaGraphWriter生成圖表,該EndpointDataSource是空的。

如果嘗試使用其他標準機制來注入早期行為,情況也是如此,如IStartupFilter- Startup.Configure()執行之前 呼叫 ,因此EndpointDataSource將為空。

同樣,您不能只是在Program.Main呼叫IHostBuilder.Build()來構建一個Host,然後使用IHost.Services:來訪問服務,直到您呼叫IHost.Run,並且伺服器已啟動,否則您的終結點列表將為空!

這些限制可能不是問題,具體取決於您要實現的目標。對我來說,單元測試方法可以解決我的大多數問題。

無論使用哪種方法,都只能生成本文中顯示的“預設”終結點圖。這隱藏了很多真正有用的資訊,例如哪些節點生成了終結點。在下一篇文章中,我將展示如何建立自定義圖形編寫器,以便您可以生成自己的圖形。

總結

在這篇文章中,我展示瞭如何使用DfaGraphWriterEndpointDataSource建立應用程式中所有終結點的圖形。我展示瞭如何建立中介軟體終結點來公開此資料,以及如何將這種中介軟體與分支中介軟體策略一起用作終結點路由。

我還展示瞭如何使用簡單的整合測試來生成圖形資料而無需執行您的應用程式。這避免了公開(可能敏感)的終結點圖,同時仍然允許輕鬆訪問資料。

最後,我討論了何時可以在應用程式的生命週期中生成圖形。該EndpointDataSource未填充,直到後Server(Kestrel)已經開始,所以你主要限於在請求上下文訪問資料。IHostedServiceIStartupFilter執行得太早以至於無法訪問資料,IHostBuilder.Build()只是構建DI容器,而沒有構建中介軟體管道。