您可以使用Bitmap库生成图形验证码。首先,创建一个生成的工具类。代码如下:
public class VerifyCodeHelper
{
public static Bitmap CreateVerifyCode(out string code)
{
//Create a Bitmap object and draw
Bitmap bitmap = new Bitmap(200, 60);
Graphics graph = Graphics.FromImage(bitmap);
graph.FillRectangle(new SolidBrush(Color.White), 0, 0, 200, 60);
Font font = new Font(FontFamily.GenericSerif, 48, FontStyle.Bold, GraphicsUnit.Pixel);
Random r = new Random();
string letters = "0123456789";
StringBuilder sb = new StringBuilder();
//Add random 4 numbers
for (int x = 0; x < 4; x++)
{
string letter = letters.Substring(r.Next(0, letters.Length - 1), 1);
sb.Append(letter);
graph.DrawString(letter, font, new SolidBrush(Color.Black), x * 38, r.Next(0, 15));
}
code = sb.ToString();
//Confuse the background
Pen linePen = new Pen(new SolidBrush(Color.Black), 2);
for (int x = 0; x < 6; x++)
graph.DrawLine(linePen, new Point(r.Next(0, 199), r.Next(0, 59)), new Point(r.Next(0, 199), r.Next(0, 59)));
return bitmap;
}
}
努吉特包:
<ItemGroup>
<PackageReference Include="System.Drawing.Common" Version="6.0.0" />
</ItemGroup>
控制器:
[ApiController]
public class VerifyCodeController : Controller
{
private readonly IDistributedCache _distributedCache;
public VerifyCodeController(IDistributedCache distributedCache)
{
_distributedCache = distributedCache;
}
[Route("get_captcha")]
public Object VerifyCode()
{
string code = "";
Bitmap bitmap = VerifyCodeHelper.CreateVerifyCode(out code);
_distributedCache.SetString("code", code);
base.HttpContext.Session.SetString("CheckCode", code);
MemoryStream stream = new MemoryStream();
bitmap.Save(stream, ImageFormat.Gif);
return File(stream.ToArray(), "image/gif");
}
}
startup.cs配置:(如果api调用异常,请仔细检查配置)
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddDistributedMemoryCache();
services.AddSession(options => {
options.IdleTimeout = TimeSpan.FromMinutes(1);
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseStaticFiles();
app.UseSession();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
调用 get_captcha 路由:
更多自定义用法可以参考这篇文章:
.Net Core Bitmap 位图处理