当前位置: 代码网 > it编程>编程语言>Asp.net > .net core 中 WebApiClientCore的使用示例代码

.net core 中 WebApiClientCore的使用示例代码

2024年05月18日 Asp.net 我要评论
webapiclient接口注册与选项1 配置文件中配置httpapioptions选项配置示例 "iuserapi": { "httphost": "http://www.webappicli

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,通俗来讲有以下几个要点:

  • 使用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, "laojiu@qq.com");

请求内容

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":"laojiu@qq.com"}]

异常处理

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使用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com