使用WebApiClientCore快速编写Api调用类
开发微信小程序或者网站后台是,难免要对接一些外部的API,传统调用是使用HttpClient或者WebClient,然而写起来相当繁琐!
为此老九写了个WebApiClient并且推出了.Net Core版本的WebApiClientCore,本文简单介绍如何使用:
1、安装包
install-package webapiclientcore
install-package webapiclientcore.oauth
2、定义Api调用接口
using WebApiClientCore;
using WebApiClientCore.Attributes;
using WebApiClientCore.Extensions.OAuths;
using WebApiClientCore.HttpContents;
namespace Demo{
[HttpHost("https://aip.baidubce.com/")] //定义根路径
public interface IBaiduApi : IHttpApi
{
[HttpPost("rest/2.0/ocr/v1/business_license ")] //定义根路径后面的路径
[BaiduAccessToken] //定义使用BaiduAccessToken特性,其实就是自动将获取到的accesstoken添加到请求参数
ITask<dynamic> AnalysiseLicense([FormContent] LicenseFile image); //定义传入的参数是作为form表单数据,如果是json的可以修改为JsonContent,并且将结果抓换成dynamic类型,可以根据需要写个对应的类,自动转换成该类。
}
public class BaiduAccessTokenAttribute : OAuthTokenAttribute //定义BaiduAccessToken特性
{
protected override async void UseTokenResult(ApiRequestContext context, TokenResult tokenResult) //重写方法
{
context.HttpContext.RequestMessage.AddUrlQuery("access_token", tokenResult.Access_token); //在请求中加入querystring数据
}
}
public class LicenseFile //定义请求参数对象
{
public string image { get; set; }
public string url { get; set; }
public bool risk_warn { get; set; } = false;
}
}
3、配置Startup.cs
在Startup.cs中的ConfigureServices中添加注入:
services.AddHttpApi<IBaiduApi>();//添加定义的接口
services.AddClientCredentialsTokenProvider<IBaiduApi>(c =>
{ //设置oAuth配置
c.Endpoint = new Uri("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials");
c.UseRefreshToken = false;
c.Credentials.Client_id = "百度的Ak";
c.Credentials.Client_secret = "百度的AppSecret";
});
4、Controller中调用
public class V2Controller : Controller
{
private readonly IBaiduApi baiduApi;
public V2Controller(IBaiduApi baiduApi)
{
this.baiduApi = baiduApi; //获取注入的api对象
}
public async Task<IActionResult> AnalyseLicense(IFormFile[] file)
{
try
{
var data = new LicenseFile() { image = "data:" + file[0].ContentType +";base64,"+ getFileBase64(file[0].OpenReadStream()) };
// var data = new LicenseFile() { url = "https://www.generalwatertech.com/uploadfiles/2020/01/20200109175314541.jpg" };
var x = await baiduApi.AnalysiseLicense( data); //调用接口
return new JsonResult(
new
{
data = x,
success = true,
message = "",
code = 0
}
);
}
catch (Exception ex)
{
return null;
}
}
public static String getFileBase64(Stream filestream)
{
byte[] arr = new byte[filestream.Length];
filestream.Read(arr, 0, (int)filestream.Length);
string base64 = Convert.ToBase64String(arr);
filestream.Close();
return base64 ;
}
}
至此完成了百度卡证识别中的执照识别接口调用,需要的时候增加IBaiduApi里面的方法接口即可!