關于.Net 7.0 RC gRPC JSON 轉碼為 Swagger/OpenAPI文檔的注意事項
大家好,我是失業在家,正在找工作的博主Jerry,找工作之余,看到.Net 7.0 RC2發布了,就想測試下.Net 7.0 RC2 gRPC JSON 轉碼為 Swagger/OpenAPI文檔的特性,這個特性大大提高了測試gRPC接口的方便性。本來以為按照官方文檔,也就是幾分鐘的事,結果搞了幾個小時才成功!我也是服了官方的文檔了!
我現在把要要注意的幾個問題列出來,給要使用這個特性的程序員節約一點時間。
一、官方文檔對gRPC JSON 轉碼配置描述不完整
這個特性是基于gRPC JSON 轉碼配置的,也就是說我們先要配置gRPC JSON 轉碼才能使用該特性。
// Add services to the container. builder.Services.AddGrpc().AddJsonTranscoding();
如上我們在Program.cs中的代碼,先要先加上gRPC JSON轉碼。如果按照官方文檔直接在.proto文件的rpc方法中增加option
option (google.api.http) = { get: "/v1/greeter/{name}" };
則編譯會報錯,“Option "(google.api.http)" unknown. Ensure that your proto definition file imports the proto which defines the option.”
要先按照另一個官方文檔專門配置gRPC JSON轉碼。要在.proto文件中增加“import "google/api/annotations.proto";
import "google/api/annotations.proto";
二、官方文檔對gRPC JSON 轉碼配置描述不清楚
加上了import..., 還是會編譯出錯,"Import "google/api/annotations.proto" was not found or had errors.".
原因就是文檔里的這一句“Imported from the google/api/annotations.proto file. The google/api/http.proto and google/api/annotations.proto files need to be in the project.”實在說的不清楚。
其實,我們要在我們項目的根目錄建立google文件夾,然后在下面建立api文件夾,再把這兩個文件放到里面。如下截圖:

然后還要確保項目文件中,不要把這兩個文件包含到Protobuf節點中。不然在啟動程序的時候就會出現對象轉換失敗的錯誤,“[A]Google.Protobuf.ExtensionValue`1[Google.Api.HttpRule] cannot be cast to [B]Google.Protobuf.ExtensionValue`1[Google.Api.HttpRule]. Type A originates from 'Google.Protobuf, Version=3.19.4.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604' in the context 'Default' at location 'D:\\Study\\Test\\GrpcService4TestSwagger\\bin\\Debug\\net7.0\\Google.Protobuf.dll'. Type B originates from 'Google.Protobuf, Version=3.19.4.0, Culture=neutral, PublicKeyToken=a7d26565bac4d604' in the context 'Default' at location 'D:\\Study\\Test\\GrpcService4TestSwagger\\bin\\Debug\\net7.0\\Google.Protobuf.dll'”
<ItemGroup> <Protobuf Include="Protos\greet.proto" GrpcServices="Server" /> </ItemGroup>
這樣就算配置gRPC JSON轉碼完成了,程序終于可以運行起來了。
三、官方文檔上的代碼片段不正確
這時候,如果你訪問Swagger的頁面還是會出錯,“System.IO.FileNotFoundException:“Could not find file 'D:\Study\Test\GrpcService4TestSwagger\bin\Debug\net7.0\Server.xml”,我真是服了這個官方文檔了,要把官方文檔給的代碼:
var filePath = Path.Combine(System.AppContext.BaseDirectory, "Server.xml"); c.IncludeXmlComments(filePath); c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
改成這樣才行:
var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; var filePath = Path.Combine(AppContext.BaseDirectory, xmlFilename); c.IncludeXmlComments(filePath); c.IncludeGrpcXmlComments(filePath, includeControllerXmlComments: true);
終于, gRPC JSON 轉碼為 Swagger/OpenAPI文檔的特性可以成功運行了。

四、找工作
? 博主有15年以上的軟件技術實施經驗(Technical Leader),專注于微服務和云原生(K8s)軟件架構設計、專注于 .Net Core\Java開發和Devops構建發布。
? 博主10年以上的軟件交付管理經驗(Project Manager & Product Ower),致力于敏捷(Scrum)項目管理、軟件產品業務需求分析和原型設計。
? 博主熟練配置和使用 Microsoft Azure云。
? 博主為人誠懇,積極樂觀,工作認真負責。
我家在廣州,也可以去深圳工作。做架構和項目管理都可以。有工作機會推薦的朋友可以加我微信 15920128707,微信名字叫Jerry。
浙公網安備 33010602011771號