首先我们先看看实现人脸识别的数据流向
可以看到所需写的接口有两个,一个是注册接口,一个是登录接口。
注册接口除了普通注册所需的json信息外,还需要一个自拍的照片。
登录接口只需要一张自拍即可。
然后再看看我们DDD的架构
若不增加实体,新增接口需要修改的是Contorller,Application,Domain三个层,Contorller层只提供接口,Application层只负责Domain层方法的调用和参数的传递,Domain层主管领域业务逻辑,要实现人脸识别需要在此调用外部接口,对接人脸库。
若有实体需要增加,要修改Entity(领域实体),Factory(工厂类),以及和EFCORE有关的Repository。
在普通注册的基础上多了图片的传递,因此实体多一个字段是记录图片的路径
在userPo.cs增加ImgSrc,如下示例
工厂类和实体类同理,增加ImgSrc字段
然后在control层开始编写接口,一层层往下增加接口有关方法
应用层判断一下传入的json和图片是否为空
最后在领域层编写有关业务逻辑的方法
public string xxx(string InputJson, IFormFile formfile)
{
JObject jo = JObject.Parse(InputJson);
UserEntity userEntity = userFactory.CreateAiUser(jo);
UserPo userPo = userEntity.GetUserPo();
//存入人脸图片保存路径
userPo.ImgSrc = "http://ip/FaceDatabasePath/" + userPo.Id+".jpg";
SortedList<string, object> keyValuePairs = new SortedList<string, object>();
//将userid添加进para
keyValuePairs.Add("userId", userPo.Id);
string para = JsonConvert.SerializeObject(keyValuePairs);
string result = "";
//对接人脸录入接口
using (HttpClient _client = new HttpClient())
{
var multiContent = new MultipartFormDataContent();
var ms = new MemoryStream();
formfile.CopyTo(ms);
var fileBytes = ms.ToArray();
var fileContent = new ByteArrayContent(fileBytes);
//录入信息传出
multiContent.Add(new StringContent(para), "InputJson");
multiContent.Add(fileContent, "file", Path.GetFileName(formfile.Name));
string url = ConfigHelper.GetConfig("Aiconfig:FaceRegister");
HttpResponseMessage response = _client.PostAsync(url, multiContent).Result;
result = response.Content.ReadAsStringAsync().Result;
}
//反序列化返回的信息
var json = JsonConvert.DeserializeObject<SortedList<string, object>>(result);
var msg = Convert.ToString(json["Msg"]);
if (Convert.ToString(json["ErrCode"]) == "1")
{
userRepository.SaveUser(userPo);
return "注册成功";
}
else
{
throw new Exception(msg);
}
}
整合全过程如此,人脸识别有关的方法是使用python编写的调用库,可以参考git中的example
https://github.com/ageitgey/face_recognition