.net core 中 WebApiClientCore的使用

2022-12-09 18:03:16

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.comhttp://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,通俗來講有以下幾個要點:

  1. 使用HTTP PATCH請求方法;
  2. 請求body為描述多個opration的資料json內容;
  3. 請求的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("http://wmsapi.dev.gct-china.com/")]//請求地址域名
    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>();