.NET Core 使用 WebApiClient.JIT 调用第三方接口

摘要:
publicstaticclassxxxHttpsModule{publicstaticIServiceCollectionRegister{services.TryAddSingleton();voidconfig{c.HttpHost=newUri;//AppSettings.json中的服务器地址c.GlobalFilters.Add;}services.AddHttpApi().ConfigureHttpApiConfig;//注入接口returnservices;}}AddHttpApi是一个扩展方法,这样写只是为了在多次使用时,看起来更协调。//////基于DependencyInjection的扩展///publicstaticclassDependencyInjectionExtensions{//////添加HttpApi///返回HttpApi工厂//////接口类型//////publicstaticHttpApiFactoryBuilderAddHttpApiwhereTInterface:class,IHttpApi{returnnewHttpApiFactoryBuilder;}}IxxxApi接口中的内容就是第三方接口的内容[TraceFilter]//这个设置可以将日志输入到控制台publicinterfaceIxxxApi:IHttpApi{//////创建xxx信息//////实体///[Timeout][HttpPost]ITask˂AjaxResponse˂List˃˃GetxxxPagedList;//////获取xxx信息//////页码///[Timeout][HttpGet]ITask˂AjaxResponse˂List˃˃GetxxxPagedList;}2.创建HttpApi实例工厂创建器类,具体内容如下。目前没有修改过里面的内容。

开始前首先通过 NuGet 引入包,当前使用版本为 v1.0.9,发布日期 2019年5月21日

.NET Core 使用 WebApiClient.JIT 调用第三方接口第1张

Github:https://github.com/dotnetcore/WebApiClient/tree/WebApiClient.JITAOT 注意底部有Wiki文档对使用非常有帮助,请仔细阅读。

1.新建 xxxHttpsModule 并在StartupConfigureServices 中注入。(单独新建 HttpsModule 是为了将不同的业务分离)

public static class xxxHttpsModule
{
    public static IServiceCollection Register(IServiceCollection services, IConfigurationRoot appConfiguration)
    {
        services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

        void config(HttpApiConfig c)
        {
            c.HttpHost = new Uri(appConfiguration["Server:Url"]);//AppSettings.json 中的服务器地址
            c.GlobalFilters.Add(new DefaultHeaderAttribute(appConfiguration));
        }

        services.AddHttpApi<IxxxApi>().ConfigureHttpApiConfig(config);//注入接口

        return services;
    }
}

AddHttpApi 是一个扩展方法,这样写只是为了在多次使用时,看起来更协调。

/// <summary>
/// 基于DependencyInjection的扩展
/// </summary>
public static class DependencyInjectionExtensions
{
    /// <summary>
    /// 添加HttpApi
    /// 返回HttpApi工厂
    /// </summary>
    /// <typeparam name="TInterface">接口类型</typeparam>
    /// <param name="services"></param>
    /// <returns></returns>
    public static HttpApiFactoryBuilder<TInterface> AddHttpApi<TInterface>(this IServiceCollection services)
        where TInterface : class, IHttpApi
    {
        return new HttpApiFactoryBuilder<TInterface>(services);
    }
}

IxxxApi 接口中的内容就是第三方接口的内容

[TraceFilter(OutputTarget = OutputTarget.Console)]//这个设置可以将日志输入到控制台
public interface IxxxApi : IHttpApi
{
    /// <summary>
    /// 创建xxx信息
    /// </summary>
    /// <param name="input">实体</param>
    /// <returns></returns>
    [Timeout(10000)]
    [HttpPost("/api/v2/x/xxx")]
    ITask<AjaxResponse<List<xxxApiDto>>> GetxxxPagedList([JsonContent] xxxDto input);

    /// <summary>
    /// 获取xxx信息
    /// </summary>
    /// <param name="pageIndex">页码</param>
    /// <returns></returns>
    [Timeout(10000)]
    [HttpGet("/api/v2/x/xxx")]
    ITask<AjaxResponse<List<xxxApiDto>>> GetxxxPagedList(int pageIndex);
}

2.创建HttpApi 实例工厂创建器类,具体内容如下。目前没有修改过里面的内容。

using System;
using WebApiClient;
using System.Net.Http;
using Microsoft.Extensions.DependencyInjection;

/// <summary>
/// HttpApi实例工厂创建器
/// </summary>
/// <typeparam name="TInterface"></typeparam>
public class HttpApiFactoryBuilder<TInterface> where TInterface : class, IHttpApi
{
    private bool keepCookieContainer = true;

    private TimeSpan lifeTime = TimeSpan.FromMinutes(2d);

    private TimeSpan cleanupInterval = TimeSpan.FromSeconds(10d);

    private Action<HttpApiConfig, IServiceProvider> configOptions;

    private Func<IServiceProvider, HttpMessageHandler> handlerFactory;


    /// <summary>
    /// HttpApi实例工厂创建器
    /// </summary>
    /// <param name="services"></param>
    public HttpApiFactoryBuilder(IServiceCollection services)
    {
        services.AddSingleton<IHttpApiFactory<TInterface>, HttpApiFactory<TInterface>>(p =>
        {
            return new HttpApiFactory<TInterface>()
                .SetLifetime(this.lifeTime)
                .SetCleanupInterval(this.cleanupInterval)
                .SetKeepCookieContainer(this.keepCookieContainer)
                .ConfigureHttpMessageHandler(() => this.handlerFactory?.Invoke(p));
        });

        services.AddTransient(p =>
        {
            var factory = p.GetRequiredService<IHttpApiFactory<TInterface>>();
            factory.ConfigureHttpApiConfig(c =>
            {
                c.ServiceProvider = p;
                this.configOptions?.Invoke(c, p);
            });
            return factory.CreateHttpApi();
        });
    }

    /// <summary>
    /// 配置HttpApiConfig
    /// </summary>
    /// <param name="configOptions">配置选项</param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> ConfigureHttpApiConfig(Action<HttpApiConfig> configOptions)
    {
        if (configOptions == null)
        {
            throw new ArgumentNullException(nameof(configOptions));
        }
        return this.ConfigureHttpApiConfig((c, p) => configOptions.Invoke(c));
    }


    /// <summary>
    /// 配置HttpApiConfig
    /// </summary>
    /// <param name="configOptions">配置选项</param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> ConfigureHttpApiConfig(Action<HttpApiConfig, IServiceProvider> configOptions)
    {
        this.configOptions = configOptions ?? throw new ArgumentNullException(nameof(configOptions));
        return this;
    }

    /// <summary>
    /// 配置HttpMessageHandler的创建
    /// </summary>
    /// <param name="handlerFactory">创建委托</param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> ConfigureHttpMessageHandler(Func<HttpMessageHandler> handlerFactory)
    {
        if (handlerFactory == null)
        {
            throw new ArgumentNullException(nameof(handlerFactory));
        }
        return this.ConfigureHttpMessageHandler(p => handlerFactory.Invoke());
    }

    /// <summary>
    /// 配置HttpMessageHandler的创建
    /// </summary>
    /// <param name="handlerFactory">创建委托</param>
    /// <exception cref="ArgumentNullException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> ConfigureHttpMessageHandler(Func<IServiceProvider, HttpMessageHandler> handlerFactory)
    {
        this.handlerFactory = handlerFactory ?? throw new ArgumentNullException(nameof(handlerFactory));
        return this;
    }

    /// <summary>
    /// 置HttpApi实例的生命周期
    /// </summary>
    /// <param name="lifeTime">生命周期</param>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> SetLifetime(TimeSpan lifeTime)
    {
        if (lifeTime <= TimeSpan.Zero)
        {
            throw new ArgumentOutOfRangeException(nameof(lifeTime));
        }
        this.lifeTime = lifeTime;
        return this;
    }


    /// <summary>
    /// 获取或设置清理过期的HttpApi实例的时间间隔
    /// </summary>
    /// <param name="interval">时间间隔</param>
    /// <exception cref="ArgumentOutOfRangeException"></exception>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> SetCleanupInterval(TimeSpan interval)
    {
        if (interval <= TimeSpan.Zero)
        {
            throw new ArgumentOutOfRangeException(nameof(interval));
        }
        this.cleanupInterval = interval;
        return this;
    }

    /// <summary>
    /// 设置是否维护使用一个CookieContainer实例 该实例为首次创建时的CookieContainer
    /// </summary>
    /// <param name="keep">true维护使用一个CookieContainer实例</param>
    /// <returns></returns>
    public HttpApiFactoryBuilder<TInterface> SetKeepCookieContainer(bool keep)
    {
        this.keepCookieContainer = keep;
        return this;
    }
}

3.调用就和我们自己写的接口一样在构造函数中注入使用,如果不告诉你这是一个第三方接口,完全感觉不出来。

4.WebApiClient 还可以通过 AliasAs 属性自定义字段名称


[Serializable]
public class xxxApiDto
{
    /// <summary>
    /// 序列号
    /// </summary>
    [AliasAs("serialNum")]
    public string SerialNumber { get; set; }
}

目前发现如果在 xxxApiDto 类中属性存在类时, AliasAs 则不会被识别,目前的解决方案是使用 [JsonProperty(PropertyName = "serialNum")],再通过JsonConvert.SerializeObject(xxx) 转换成 JSON 字符串。

5.请求注入 Headers ,可以通过继承ApiActionFilterAttribute 类,然后重写OnBeginRequestAsync 实现。

免责声明:文章转载自《.NET Core 使用 WebApiClient.JIT 调用第三方接口》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇第14次作业Flume安装部署下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

CSS hover伪类改变其他元素的样式

重要的一点,hover在父元素上,对子元素进行样式调整。也可以#firdiv:hover~.se改变所有同级的元素总结一下:hover对同级别的元素改变样式,改变的是相邻兄弟元素的样式,即一个元素的样式;对元素的子元素应用hover改变样式,可以同时起作用。利用伪类改变其他元素的样式,其他元素须是hover元素的子元素。...

OpenWrt路由器通过LuCI界面实现Guest SSID功能

此外,OpenWrt路由器上的访客SSID不会受到主SSID的MAC地址过滤功能的影响,这是番茄路由器的优势。...

小程序实现单选多选功能

applet的单选组件和复选框组件的样式只提供了变化的颜色,这显然不足以满足实际的项目需求,因此您可以自己模拟。脚注:小程序不支持dom1的操作。多个框的模拟实现:实现思路:想法非常简单。使用选中的属性绑定每个选项。类型为布尔型。单击以反转!...

Cesium快速上手10-Viewer Entities组合

src=Box.html&label=Geometriesimage.pngbox就是立方体cylinder是圆锥圆柱varviewer=newCesium.Viewer;varblueBox=viewer.entities.add;varredBox=viewer.entities.add;varoutlineOnly=viewer.entitie...

js学习-es6实现枚举

最近,我大部分时间都在写dart,突然使用了js。我发现js不能直接声明枚举。目录枚举功能对象冻结()符号实现反映了不可更改值的唯一性。请注意,枚举特性枚举值不能重复,也不能修改。Switchcase可以直接判断对象。冻结()对象。方法可以冻结对象。无法更改实现constEnumSex=Object。冷冻枚举性别。人=1;安慰日志;//符号(男性)表示值co...

sql server 日志软件过大设置办法

在使用sqlserver的过程中,sql日志文件的大小将随着其增长而受到限制。1.找到相应的库--˃属性--˃恢复模式,并将其更改为简单模式。2.选择库--˃任务--˃收缩--˃文件。3.选择日志文件收缩或数据库文件收缩。删除命令后占用的空间将在此处释放。数据库ldf文件的占用空间将更改为设置的空间大小。...