.net core 中 webapiclientcore的使用示例代码-kb88凯时官网登录

来自:网络
时间:2024-06-10
阅读:

webapiclient

接口注册与选项

1 配置文件中配置httpapioptions选项

配置示例

 "iuserapi": {
    "httphost": "http://www.webappiclient.com/",
    "useparameterpropertyvalidate": false,
    "usereturnvaluepropertyvalidate": false,
    "jsonserializeoptions": {
      "ignorenullvalues": true,
      "writeindented": false
    }
  }

2 service注册

示例

services
    .configurehttpapi(configuration.getsection(nameof(iuserapi)))
    .configurehttpapi(o =>
    {
        // 符合国情的不标准时间格式,有些接口就是这么要求必须不标准
        o.jsonserializeoptions.converters.add(new jsondatetimeconverter("yyyy-mm-dd hh:mm:ss"));
    });

httpapioptions详细展示

/// 
/// 表示httpapi选项
/// 
public class httpapioptions
{
    /// 
    /// 获取或设置http服务完整主机域名
    /// 例如http://www.abc.com/或http://www.abc.com/path/
    /// 设置了httphost值,httphostattribute将失效
    /// 
    public uri? httphost { get; set; }
    /// 
    /// 获取或设置是否使用的日志功能
    /// 
    public bool uselogging { get; set; } = true;
    /// 
    /// 获取或设置请求头是否包含默认的useragent
    /// 
    public bool usedefaultuseragent { get; set; } = true;
    /// 
    /// 获取或设置是否对参数的属性值进行输入有效性验证
    /// 
    public bool . { get; set; } = true;
    /// 
    /// 获取或设置是否对返回值的属性值进行输入有效性验证
    /// 
    public bool usereturnvaluepropertyvalidate { get; set; } = true;
    /// 
    /// 获取json序列化选项
    /// 
    public jsonserializeroptions jsonserializeoptions { get; } = createjsonserializeoptions();
    /// 
    /// 获取json反序列化选项
    /// 
    public jsonserializeroptions jsondeserializeoptions { get; } = createjsondeserializeoptions();
    /// 
    /// xml序列化选项
    /// 
    public xmlwritersettings xmlserializeoptions { get; } = new xmlwritersettings();
    /// 
    /// xml反序列化选项
    /// 
    public xmlreadersettings xmldeserializeoptions { get; } = new xmlreadersettings();
    /// 
    /// 获取keyvalue序列化选项
    /// 
    public keyvalueserializeroptions keyvalueserializeoptions { get; } = new keyvalueserializeroptions();
    /// 
    /// 获取自定义数据存储的字典
    /// 
    public dictionary properties { get; } = new dictionary();
    /// 
    /// 获取接口的全局过滤器集合
    /// 
    public ilist globalfilters { get; } = new list();
    /// 
    /// 创建序列化jsonserializeroptions
    ///  
    private static jsonserializeroptions createjsonserializeoptions()
    {
        return new jsonserializeroptions
        {
            propertynamecaseinsensitive = true,
            propertynamingpolicy = jsonnamingpolicy.camelcase,
            dictionarykeypolicy = jsonnamingpolicy.camelcase,
            encoder = javascriptencoder.unsaferelaxedjsonescaping
        };
    }
    /// 
    /// 创建反序列化jsonserializeroptions
    /// 
    /// 
    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 refreshtokenasync(iserviceprovider serviceprovider, string refresh_token)
        {
           return this.refreshtokenasync(serviceprovider, refresh_token);
        }
        protected override async task requesttokenasync(iserviceprovider serviceprovider)
        {
            logininput login = new logininput();
            login.usernameoremailaddress = "admin";
            login.password = "bb123456";
            var result = await serviceprovider.getrequiredservice().requesttoken(login).retry(maxcount: 3);
            return result;
        }
    }

tokenprovider的注册

services.addtokenprovider();

oauthtokenhandler

可以自定义oauthtokenhandler官方定义是属于http消息处理器,功能与oauthtokenattribute一样,除此之外,如果因为意外的原因导致服务器仍然返回未授权(401状态码),其还会丢弃旧token,申请新token来重试一次请求。

oauthtoken在webapiclient中一般是保存在http请求的header的authrization

当token在url中时我们需要自定义oauthtokenhandler

class uriqueryoauthtokenhandler : oauthtokenhandler
{
    /// 
    /// token应用的http消息处理程序
    /// 
    /// token提供者 
    public uriqueryoauthtokenhandler(itokenprovider tokenprovider)
        : base(tokenprovider)
    {
    }
    /// 
    /// 应用token
    /// 
    /// 
    /// 
    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()
    .addoauthtokenhandler((s, tp) => new uriqueryoauthtokenhandler(tp));
//自定义tokoenprovider使用自定义oauthtokenhandler
 apibulider.addoauthtokenhandler((sp,token)=>
            {
                token=sp.getrequiredservice();
                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 patchasync(string id, jsonpatchdocument doc);
}

实例化jsonpatchdocument

var doc = new jsonpatchdocument();
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(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> getforedit([required] string id);//请求参数声明
        [httppost("api/tokenauth/authenticate")]
        itask requesttoken([jsoncontent] authenticatemodel login);
    }

基于webapiclient的扩展类

扩展类声明

/// 
    /// webapiclient扩展类
    /// 
    public static class webapiclientexentions
    {
        public static iservicecollection addwebapicliethttp(this iservicecollection services, action? 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().configurehttpapi(p => p = option);
            return services;
        }
        public static iservicecollection addwebapicliethttp(this iservicecollection services,iconfiguration configuration) where thttp : class, ihttpapi
        {
            services.addhttpapi().configurehttpapi((microsoft.extensions.configuration.iconfiguration)configuration);
            return services;
        }
        public static iservicecollection addwebapiclienthttpwithtokeprovider(this iservicecollection services, action? options = null) where thttp : class, ihttpapi
            where ttokenprovider : class, itokenprovider
        {
            services.addwebapicliethttp(options);
            services.addtokenprovider();
            return services;
        }
        public static iservicecollection addwebapiclienthttpwithtokeprovider(this iservicecollection services, iconfiguration configuration) where thttp : class, ihttpapi
            where ttokenprovider : class, itokenprovider
        {
            services.addwebapicliethttp(configuration);
            services.addtokenprovider();
            return services;
        }
    }

扩展类使用

services.addwebapiclienthttpwithtokeprovider();
返回顶部
顶部
网站地图