歡迎光臨
每天分享高質量文章

WebApiClient與Asp.net core DI的結合

1 WebApiClient

一款基於HttpClient封裝,只需要定義c#介面並修飾相關特性,即可非同步呼叫遠端http介面的客戶端庫

  • WebApiClient
  • WebApiClient.Extensions
  • WebApiClient.Tools

2 Http介面的註冊與提供

2.1 宣告遠端端http介面

public interface IBaiduApi : IHttpApi
{
    [HttpGet("/s")]
    ITask<string> GetAsync(string word);
}

2.2 遠端端http的註冊

使用HttpClientFactory管理HttpClient的建立,利用AddTypedClient建立遠端http介面的WebApiClient呼叫代理,同時給HttpApiConfig配置ServiceProvider實體。

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    services.AddHttpApiTypedClient().ConfigureHttpApiConfig((c, p) =>
    {
        c.HttpHost = new Uri("http://www.baidu.com/");
    });
}
///
/// 新增HttpApiClient的別名HttpClient
/// 

/// 介面型別
///
///配置選項
///
///
public static IHttpClientBuilder AddHttpApiTypedClient(this IServiceCollection services, Action configOptions)
where TInterface : class, IHttpApi
{
if (configOptions == null)
{
throw new ArgumentNullException(nameof(configOptions));
}

return services
.AddHttpClient()
.AddTypedClient((httpClient, provider) =>
{
var httpApiConfig = new HttpApiConfig(httpClient)
{
ServiceProvider = provider
};
configOptions.Invoke(httpApiConfig, provider);
return HttpApiClient.Create(httpApiConfig);
});
}

2.3 遠端端http介面的提供

可以使用建構式註入IBaiduApi或[FromServices]特性得到遠端介面代理實體。

public class HomeController : Controller
{   
    // GET: //
    public async Task Index([FromServices] IBaiduApi baiduApi)
    {
        var html = await baiduApi.GetAsync("WebApiClient");
        return Content(html);
    }
}

3 WebApiClient過濾器的服務提供

3.1 在介面上使用自定義LogFilter

[LogFilter]
public interface IBaiduApi : IHttpApi
{
    [HttpGet("/s")]
    ITask<string> GetAsync(string word);
}

3.2 使用context.GetService獲取服務實體

class LogFilter : ApiActionFilterAttribute
{
    public override Task OnBeginRequestAsync(ApiActionContext context)
    {
        var logger = context.GetService().CreateLogger("Baidu");
        logger.LogWarning($"request {context.ApiActionDescriptor.Name} {context.RequestMessage.RequestUri}");

        return base.OnBeginRequestAsync(context);
    }
}

3.3 日誌服務輸出日誌樣例

warn: Baidu[0]
      request GetAsync http://www.baidu.com/s?word=WebApiClient

原文地址:https://www.cnblogs.com/CKExp/p/10426170.html

贊(0)

分享創造快樂