.net core 中 WebApiClientCore的使用示例代碼
WebApiClient
接口注冊與選項
1 配置文件中配置HttpApiOptions選項
配置示例
"IUserApi": { "HttpHost": "http://www.webappiclient.com/", "UseParameterPropertyValidate": false, "UseReturnValuePropertyValidate": false, "JsonSerializeOptions": { "IgnoreNullValues": true, "WriteIndented": false } }
2 Service注冊
示例
services .ConfigureHttpApi<IUserApi>(Configuration.GetSection(nameof(IUserApi))) .ConfigureHttpApi<IUserApi>(o => { // 符合國情的不標準時間格式,有些接口就是這么要求必須不標準 o.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss")); });
HttpApiOptions詳細展示
/// <summary> /// 表示HttpApi選項 /// </summary> public class HttpApiOptions { /// <summary> /// 獲取或設置Http服務完整主機域名 /// 例如http://www.abc.com/或http://www.abc.com/path/ /// 設置了HttpHost值,HttpHostAttribute將失效 /// </summary> public Uri? HttpHost { get; set; } /// <summary> /// 獲取或設置是否使用的日志功能 /// </summary> public bool UseLogging { get; set; } = true; /// <summary> /// 獲取或設置請求頭是否包含默認的UserAgent /// </summary> public bool UseDefaultUserAgent { get; set; } = true; /// <summary> /// 獲取或設置是否對參數的屬性值進行輸入有效性驗證 /// </summary> public bool . { get; set; } = true; /// <summary> /// 獲取或設置是否對返回值的屬性值進行輸入有效性驗證 /// </summary> public bool UseReturnValuePropertyValidate { get; set; } = true; /// <summary> /// 獲取json序列化選項 /// </summary> public JsonSerializerOptions JsonSerializeOptions { get; } = CreateJsonSerializeOptions(); /// <summary> /// 獲取json反序列化選項 /// </summary> public JsonSerializerOptions JsonDeserializeOptions { get; } = CreateJsonDeserializeOptions(); /// <summary> /// xml序列化選項 /// </summary> public XmlWriterSettings XmlSerializeOptions { get; } = new XmlWriterSettings(); /// <summary> /// xml反序列化選項 /// </summary> public XmlReaderSettings XmlDeserializeOptions { get; } = new XmlReaderSettings(); /// <summary> /// 獲取keyValue序列化選項 /// </summary> public KeyValueSerializerOptions KeyValueSerializeOptions { get; } = new KeyValueSerializerOptions(); /// <summary> /// 獲取自定義數據存儲的字典 /// </summary> public Dictionary<object, object> Properties { get; } = new Dictionary<object, object>(); /// <summary> /// 獲取接口的全局過濾器集合 /// </summary> public IList<IApiFilter> GlobalFilters { get; } = new List<IApiFilter>(); /// <summary> /// 創建序列化JsonSerializerOptions /// </summary> private static JsonSerializerOptions CreateJsonSerializeOptions() { return new JsonSerializerOptions { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DictionaryKeyPolicy = JsonNamingPolicy.CamelCase, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; } /// <summary> /// 創建反序列化JsonSerializerOptions /// </summary> /// <returns></returns> private static JsonSerializerOptions CreateJsonDeserializeOptions() { var options = CreateJsonSerializeOptions(); options.Converters.Add(JsonCompatibleConverter.EnumReader); options.Converters.Add(JsonCompatibleConverter.DateTimeReader); return options; } }
Uri(url)拼接規則
所有的Uri拼接都是通過Uri(Uri baseUri, Uri relativeUri)這個構造器生成。
帶/
結尾的baseUri
http://a.com/
+b/c/d
=http://a.com/b/c/d
http://a.com/path1/
+b/c/d
=http://a.com/path1/b/c/d
http://a.com/path1/path2/
+b/c/d
=http://a.com/path1/path2/b/c/d
不帶/
結尾的baseUri
http://a.com
+b/c/d
=http://a.com/b/c/d
http://a.com/path1
+b/c/d
=http://a.com/b/c/d
http://a.com/path1/path2
+b/c/d
=http://a.com/path1/b/c/d
事實上http://a.com
與http://a.com/
是完全一樣的,他們的path都是/
,所以才會表現一樣。為了避免低級錯誤的出現,請使用的標準baseUri書寫方式,即使用/
作為baseUri的結尾的第一種方式。
OAuths&Token
推薦使用自定義TokenProvider
public class TestTokenProvider : TokenProvider { private readonly IConfiguration _configuration; public TestTokenProvider(IServiceProvider services,IConfiguration configuration) : base(services) { _configuration = configuration; } protected override Task<TokenResult> RefreshTokenAsync(IServiceProvider serviceProvider, string refresh_token) { return this.RefreshTokenAsync(serviceProvider, refresh_token); } protected override async Task<TokenResult> RequestTokenAsync(IServiceProvider serviceProvider) { LoginInput login = new LoginInput(); login.UserNameOrEmailAddress = "admin"; login.Password = "bb123456"; var result = await serviceProvider.GetRequiredService<ITestApi>().RequestToken(login).Retry(maxCount: 3); return result; } }
TokenProvider的注冊
services.AddTokenProvider<ITestApi,TestTokenProvider>();
OAuthTokenHandler
可以自定義OAuthTokenHandler官方定義是屬于http消息處理器,功能與OAuthTokenAttribute一樣,除此之外,如果因為意外的原因導致服務器仍然返回未授權(401狀態碼),其還會丟棄舊token,申請新token來重試一次請求。
OAuthToken在webapiclient中一般是保存在http請求的Header的Authrization
當token在url中時我們需要自定義OAuthTokenHandler
class UriQueryOAuthTokenHandler : OAuthTokenHandler { /// <summary> /// token應用的http消息處理程序 /// </summary> /// <param name="tokenProvider">token提供者</param> public UriQueryOAuthTokenHandler(ITokenProvider tokenProvider) : base(tokenProvider) { } /// <summary> /// 應用token /// </summary> /// <param name="request"></param> /// <param name="tokenResult"></param> protected override void UseTokenResult(HttpRequestMessage request, TokenResult tokenResult) { // var builder = new UriBuilder(request.RequestUri); // builder.Query += "mytoken=" + Uri.EscapeDataString(tokenResult.Access_token); // request.RequestUri = builder.Uri; var uriValue = new UriValue(request.RequestUri).AddQuery("myToken", tokenResult.Access_token); request.RequestUri = uriValue.ToUri(); } }
AddQuery是請求的的url中攜帶token的key
自定義OAuthTokenHandler的使用
services .AddHttpApi<IUserApi>() .AddOAuthTokenHandler((s, tp) => new UriQueryOAuthTokenHandler(tp)); //自定義TokoenProvider使用自定義OAuthTokenHandler apiBulider.AddOAuthTokenHandler<UrlTokenHandler>((sp,token)=> { token=sp.GetRequiredService<TestTokenProvider>(); return new UrlTokenHandler(token); },WebApiClientCore.Extensions.OAuths.TypeMatchMode.TypeOrBaseTypes);
OAuthToken 特性
OAuthToken可以定義在繼承IHttpApi的接口上也可以定義在接口的方法上
在使用自定義TokenProvier時要注意OAuthToken特性不要定義在具有請求token的Http請求定義上
Patch請求
json patch是為客戶端能夠局部更新服務端已存在的資源而設計的一種標準交互,在RFC6902里有詳細的介紹json patch,通俗來講有以下幾個要點:
- 使用HTTP PATCH請求方法;
- 請求body為描述多個opration的數據json內容;
- 請求的Content-Type為application/json-patch+json;
聲明Patch方法
public interface IUserApi { [HttpPatch("api/users/{id}")] Task<UserInfo> PatchAsync(string id, JsonPatchDocument<User> doc); }
實例化JsonPatchDocument
var doc = new JsonPatchDocument<User>(); doc.Replace(item => item.Account, "laojiu"); doc.Replace(item => item.Email, "[email protected]");
請求內容
PATCH /api/users/id001 HTTP/1.1 Host: localhost:6000 User-Agent: WebApiClientCore/1.0.0.0 Accept: application/json; q=0.01, application/xml; q=0.01 Content-Type: application/json-patch+json [{"op":"replace","path":"/account","value":"laojiu"},{"op":"replace","path":"/email","value":"[email protected]"}]
異常處理
try { var model = await api.GetAsync(); } catch (HttpRequestException ex) when (ex.InnerException is ApiInvalidConfigException configException) { // 請求配置異常 } catch (HttpRequestException ex) when (ex.InnerException is ApiResponseStatusException statusException) { // 響應狀態碼異常 } catch (HttpRequestException ex) when (ex.InnerException is ApiException apiException) { // 抽象的api異常 } catch (HttpRequestException ex) when (ex.InnerException is SocketException socketException) { // socket連接層異常 } catch (HttpRequestException ex) { // 請求異常 } catch (Exception ex) { // 異常 }
請求重試
使用ITask<>異步聲明,就有Retry的擴展,Retry的條件可以為捕獲到某種Exception或響應模型符合某種條件。
GetNumberTemplateForEditOutput put = new GetNumberTemplateForEditOutput(); var res = await _testApi.GetForEdit(id).Retry(maxCount: 1).WhenCatchAsync<ApiResponseStatusException>(async p => { if (p.StatusCode == HttpStatusCode.Unauthorized) { await Token();//當http請求異常時報錯,重新請求一次,保證token一直有效 } }); put = res.Result; return put;
API接口處理
使用ITask<>異步聲明
[HttpHost("請求地址")]//請求地址域名 public interface ITestApi : IHttpApi { [OAuthToken]//權限 [JsonReturn]//設置返回格式 [HttpGet("/api/services/app/NumberingTemplate/GetForEdit")]//請求路徑 ITask<AjaxResponse<GetNumberTemplateForEditOutput>> GetForEdit([Required] string id);//請求參數聲明 [HttpPost("api/TokenAuth/Authenticate")] ITask<string> RequestToken([JsonContent] AuthenticateModel login); }
基于WebApiClient的擴展類
擴展類聲明
/// <summary> /// WebApiClient擴展類 /// </summary> public static class WebApiClientExentions { public static IServiceCollection AddWebApiClietHttp<THttp>(this IServiceCollection services, Action<HttpApiOptions>? options = null) where THttp : class, IHttpApi { HttpApiOptions option = new HttpApiOptions(); option.JsonSerializeOptions.Converters.Add(new JsonDateTimeConverter("yyyy-MM-dd HH:mm:ss")); option.UseParameterPropertyValidate = true; if(options != null) { options.Invoke(option); } services.AddHttpApi<THttp>().ConfigureHttpApi(p => p = option); return services; } public static IServiceCollection AddWebApiClietHttp<THttp>(this IServiceCollection services,IConfiguration configuration) where THttp : class, IHttpApi { services.AddHttpApi<THttp>().ConfigureHttpApi((Microsoft.Extensions.Configuration.IConfiguration)configuration); return services; } public static IServiceCollection AddWebApiClientHttpWithTokeProvider<THttp, TTokenProvider>(this IServiceCollection services, Action<HttpApiOptions>? options = null) where THttp : class, IHttpApi where TTokenProvider : class, ITokenProvider { services.AddWebApiClietHttp<THttp>(options); services.AddTokenProvider<THttp,TTokenProvider>(); return services; } public static IServiceCollection AddWebApiClientHttpWithTokeProvider<THttp, TTokenProvider>(this IServiceCollection services, IConfiguration configuration) where THttp : class, IHttpApi where TTokenProvider : class, ITokenProvider { services.AddWebApiClietHttp<THttp>(configuration); services.AddTokenProvider<THttp, TTokenProvider>(); return services; } }
擴展類使用
services.AddWebApiClientHttpWithTokeProvider<ITestApi, TestTokenProvider>();
到此這篇關于.net core 中 WebApiClientCore的使用示例代碼的文章就介紹到這了,更多相關.net core 中 WebApiClientCore使用內容請搜索以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持!
