使用.net6+webApi接入阿里云2.0图形验证码
创建一个.NET 6 Web API项目来接入阿里云2.0图形验证码涉及到几个步骤,包括配置阿里云SDK、生成验证码、验证验证码等。以下是一个基本的教程步骤:
1. 安装阿里云SDK
dotnet add package AlibabaCloud.SDK.Captcha20230305 --version 1.1.3
2.配置阿里云账户信息
在你的Web API项目中,创建一个配置文件或在appsettings.json中添加阿里云的AccessKey ID和AccessKey Secret:
{
"AliyunCaptcha": {
"AccessKeyId": "你的AccessKeyId",
"AccessKeySecret": "你的AccessKeySecret"
},
// 其他配置...
}
3.创建验证码服务
创建一个服务类来处理与阿里云验证码相关的逻辑。你需要使用阿里云SDK生成验证码和验证用户输入的验证码:
using AlibabaCloud.SDK.Captcha20230305;
using AlibabaCloud.SDK.Captcha20230305.Models;
using AlibabaCloud.TeaUtil;
using AlibabaCloud.TeaUtil.Models;
using Microsoft.Extensions.Configuration;
using Tea;
public class CaptchaService
{
private readonly Client _client;
public CaptchaService(IConfiguration configuration)
{
var config = new AlibabaCloud.OpenApiClient.Models.Config
{
AccessKeyId = configuration["Aliyun:AccessKeyId"],
AccessKeySecret = configuration["Aliyun:AccessKeySecret"],
Endpoint = "captcha.cn-shanghai.aliyuncs.com"
};
_client = new Client(config);
}
public async Task<VerifyIntelligentCaptchaResponse> VerifyIntelligentCaptcha(string captchaVerifyParam)
{
var verifyIntelligentCaptchaRequest = new VerifyIntelligentCaptchaRequest
{
CaptchaVerifyParam = captchaVerifyParam
};
var runtime = new RuntimeOptions();
try
{
return await _client.VerifyIntelligentCaptchaWithOptionsAsync(verifyIntelligentCaptchaRequest, runtime);
}
catch (TeaException error)
{
if (!Common.Empty(error.Code) && !Common.Empty(error.Message))
{
// 错误 SDK 的错误码
// 错误 SDK 的错误信息
// 错误 SDK 的请求 ID
// error.Data 中获取更多错误信息
throw;
}
throw;
}
catch (Exception _error)
{
var error = new TeaException(new Dictionary<string, object>
{
{ "message", _error.Message }
});
throw;
}
}
}
4. 创建API控制器
using App.WebAPI.Utilty.ApiResult;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("[controller]/[Action]")]
public class CaptchaController : ControllerBase
{
private readonly CaptchaService _captchaService;
public CaptchaController(CaptchaService captchaService)
{
_captchaService = captchaService;
}
[HttpPost]
public async Task<ApiResult> VerifyCaptcha([FromBody] CaptchaVerifyModel model)
{
try
{
var response = await _captchaService.VerifyIntelligentCaptcha(model.CaptchaVerifyParam);
Console.WriteLine(response.Body.Result.VerifyCode);
if (response.Body.Result.VerifyResult == true)
{
return ApiResultHelper.Success("验证成功", true);
}
else
{
return ApiResultHelper.Error(response.Body.Result.VerifyCode);
}
}
catch (Exception ex)
{
return ApiResultHelper.Error("服务器异常");
}
}
}
public class CaptchaVerifyModel
{
public string CaptchaVerifyParam { get; set; }
}
注意,
ApiResult
根据你实际的返回数据来定义
5.添加依赖注入
最后在你项目Program中配置依赖注入
builder.Services.AddTransient<CaptchaService>();
6.测试API
使用Postman或任何API测试工具来测试你的API。首先获取验证码,然后使用验证码进行验证。