nclient:自動類型安全.NET HTTP客戶端NClient是一種自動,類型的SAFE .NET HTTP客戶端,可以使用帶註釋的接口調用Web API方法。 NClient及其類似物之間的主要區別在於,NClient使您可以通過接口註釋ASP.NET控制器,然後使用這些接口來創建客戶端。這使您可以擺脫客戶端上不需要的依賴關係,並在沒有樣板代碼的情況下重複使用客戶端的API描述。
// WebService.dll:
public class WeatherController : ControllerBase , IWeatherFacade {
public Task < Weather > GetAsync ( string city , DateTime date ) => .. . ;
}
// WebService.Facade.dll:
[ HttpFacade , Path ( "api/[facade]" ) ]
public interface IWeatherFacade {
[ GetMethod ( "{city}" ) ]
Task < Weather > GetAsync ( [ RouteParam ] string city , [ QueryParam ] DateTime date ) ;
}
// Client.dll:
IWeatherFacade weatherFacade = NClientGallery . Clients . GetRest ( )
. For < IWeatherFacade > ( host : "http://localhost:5000" )
. WithSafeResilience ( maxRetries : 3 )
. Build ( ) ;
Weather todaysWeather = await weatherFacade . GetAsync ( city : "Chelyabinsk" , date : DateTime . Today ) ; 你喜歡它?支持該項目的開發,並播放此倉庫!
為Web服務創建客戶端可能是一個挑戰,因為除了數據傳輸之外,您還需要實現查詢構建,序列化,重試策略,映射,錯誤處理和日誌記錄,更不用說每次API的更新隨附的維護。如果您可以用一小部分努力創建客戶怎麼辦?這正是Nclient旨在通過聲明地創建客戶來實現的目標。
順便說一句,您可以為Nclient做出貢獻,而不僅僅是使用它嗎?
功能:動態模板路由;靜態路由;動態查詢參數;集合作為查詢參數;動態標題;靜態標頭;動態的身體;自動序列化和避難所化; HTTP/運輸環境;驗證;異步請求;超時;取消請求;彈性政策;響應驗證;響應映射;文件上傳/下載;通用接口;接口繼承;客戶工廠;版本控制;處理;結構化伐木;依賴注射支持。
最簡單的方法是使用Nuget安裝NClient軟件包:
dotnet add package NClient
使用NClient庫需要.NET標準2.0或更高。 NClient控制器可以與ASP.NET Core和.NET Core 3.1目標或更高的目標一起使用。
首先,您必須創建一個通過註釋來描述服務的可用端點和輸入/輸出數據的接口。之後,您可以在NClientGallery中選擇所需的客戶端類型,然後在必要時為其設置其他設置。
如果要將請求發送到第三方服務,則應創建一個界面,描述要提出請求的服務。請按照以下步驟操作:
NClient dotnet add package NClient
dotnet-nclient工具 dotnet tool install --global dotnet-nclient
dotnet nclient generate facade --api path/to/product-service-swagger.json --output MyProject/Client.cs
此命令將使用OpenAPI(Swagger)規範生成API的接口:
[ Path ( "api" ) ]
public interface IProductServiceClient
{
[ PostMethod ( "products" ) ]
Task < Product > CreateAsync ( Product product ) ;
[ GetMethod ( "products/{id}" ) ]
Task < Product > GetAsync ( [ RouteParam ] int id ) ;
}如有必要,可以更改接口。這樣做很容易,因為接口註釋與ASP.NET中控制器的註釋非常相似。 PathAttribute定義了所有接口方法的基本路徑。 PostMethodAttribute指定HTTP方法的類型和通往端點的路徑。此外,隱式註釋像ASP.NET控制器中一樣工作。例如, BodyParamAttribute屬性將被隱式設置為CreateSync方法中的乘積參數。當然,還支持路線模板。閱讀註釋和路由部分中的所有功能。
IProductServiceClient client = NClientGallery . Clients . GetRest ( )
. For < IProductServiceClient > ( host : "http://localhost:8080" )
. Build ( ) ; GetRest方法使用System.Text.Json序列化創建一個REST客戶端,並且沒有彈性策略。
IProductServiceClient client = NClientGallery . Clients . GetRest ( )
. For < IProductServiceClient > ( host : "http://localhost:8080" )
. WithNewtonsoftJsonSerialization ( )
. WithResilience ( x => x
. ForMethod ( client => ( Func < Product , Task < Product > > ) client . CreateAsync )
. Use ( maxRetries : 2 , attempt => TimeSpan . FromSeconds ( Math . Pow ( 2 , attempt ) ) ) )
.. .
. Build ( ) ;調用For方法後,您可以根據需要配置客戶端。例如,您可以用Newtonsoft.Json替換序列化器,添加重試策略等等。請參閱完整的文檔。
// Equivalent to the following request:
// curl -X POST -H "Content-type: application/json" --data "{ id: 1 }" http://localhost:8080/api/products
Product product = await client . CreateAsync ( new Product ( name : "MyProduct" ) ) ;如果要為您的ASP.NET Web服務生成客戶端,則需要為控制器提取接口並使用NClient屬性進行註釋。這些屬性與用於ASP.NET控制器的屬性非常相似。請按照以下步驟操作:
NClient.AspNetCore軟件包 dotnet add package NClient.AspNetCore
public class WeatherForecastController : ControllerBase
{
public async Task < WeatherForecast > GetAsync ( DateTime date ) =>
new WeatherForecast ( date : date , temperatureC : - 25 ) ;
}請勿使用ASP.NET屬性來註釋您的控制器,這些屬性可能會引起與您打算使用的NClient屬性的語義衝突。但是,可以無限制地使用其他屬性(包括您自己的)。
[ HttpFacade , Path ( "[controller]" ) ] // equivalent to [ApiController, Route("[controller]")]
public interface IWeatherForecastController
{
[ GetMethod ] // equivalent to [HttpGet]
Task < WeatherForecast > GetAsync ( [ QueryParam ] DateTime date ) ; // equivalent to [FromQuery]
}
public class WeatherForecastController : ControllerBase , IWeatherForecastController { .. . }接口而不是控制器中的註釋使您可以將接口放在單獨的組件中。因此,使用此接口的客戶端不取決於ASP.NET應用程序。
public interface IWeatherForecastClient : IWeatherForecastController { }如果您希望客戶類型不包含名稱中的“控制器”,或者要覆蓋客戶端的某些方法(請參閱註釋部分中的OverrideAttribute ),則應該這樣做。無需複制接口屬性,因為它們是繼承的。
public void ConfigureServices ( IServiceCollection services )
{
.. .
services . AddNClientControllers ( ) ;
}可以將AddNClientControllers方法與AddControllers方法結合使用。這使您可以將標準ASP.NET控制器與同一應用程序中的NClient控制器一起使用。
NClient軟件包 dotnet add package NClient
IWeatherForecastController client = NClientGallery . Clients . GetRest ( )
. For < IWeatherForecastController > ( host : "http://localhost:8080" )
. Build ( ) ;如果您決定遵循第四步,請使用IWeatherForecastClient接口而不是IWeatherForecastController 。
// Equivalent to the following request:
// curl -X GET -H "Content-type: application/json" http://localhost:8080/WeatherForecast?date=2021-03-13T00:15Z
WeatherForecast forecast = await client . GetAsync ( DateTime . Now ) ; 您可以在Wiki上找到Nclient文檔。
請參閱nclient中的應用程序樣本。
您正在考慮為Nclient做出貢獻嗎?偉大的!我們喜歡從社區獲得貢獻!最簡單的貢獻是使該項目成為明星。
也非常歡迎幫助文檔,提取請求,問題,評論或其他任何內容。請查看我們的貢獻指南。
值得與我們聯繫以討論任何問題的變化。我們還可以就最簡單的做事方式提供建議。

Nclient希望感謝JetBrains通過免費的開源騎手許可證為該項目提供支持。