以下是使用 Net6 WebApi 项目生成图形验证码的示例代码:

  1. 安装 NuGet 包:Microsoft.AspNetCore.Mvc.TagHelpers

  2. 在 Startup.cs 文件中添加以下代码:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;

namespace WebApplication1
{
    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.AddControllersWithViews();
            services.AddMvc();
            services.AddSession();
        }

        // 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();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseRouting();
            app.UseSession();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}
  1. 创建一个 Controller,添加以下方法:
using Microsoft.AspNetCore.Mvc;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace WebApplication1.Controllers
{
    public class CaptchaController : Controller
    {
        [HttpGet]
        public IActionResult Index()
        {
            string captchaCode = GenerateRandomCode();

            Bitmap bitmap = GenerateCaptchaImage(captchaCode);

            MemoryStream memoryStream = new MemoryStream();
            bitmap.Save(memoryStream, ImageFormat.Png);
            byte[] captchaBytes = memoryStream.ToArray();

            HttpContext.Session.SetString('captcha', captchaCode);

            return File(captchaBytes, 'image/png');
        }

        private string GenerateRandomCode()
        {
            string randomCode = "";
            Random random = new Random();
            for (int i = 0; i < 6; i++)
            {
                int num = random.Next(10);
                randomCode += num.ToString();
            }
            return randomCode;
        }

        private Bitmap GenerateCaptchaImage(string captchaCode)
        {
            int width = 120;
            int height = 40;
            Bitmap bitmap = new Bitmap(width, height);

            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.Clear(Color.White);

            Font font = new Font('Arial', 20, FontStyle.Bold);
            Brush brush = new SolidBrush(Color.FromArgb(100, 100, 100));
            graphics.DrawString(captchaCode, font, brush, 10, 10);

            for (int i = 0; i < 50; i++)
            {
                int x1 = new Random().Next(width);
                int y1 = new Random().Next(height);
                int x2 = new Random().Next(width);
                int y2 = new Random().Next(height);
                graphics.DrawLine(new Pen(Color.LightGray), x1, y1, x2, y2);
            }

            graphics.Dispose();

            return bitmap;
        }
    }
}
  1. 在 View 中添加以下代码:
<img src="@Url.Action('Index', 'Captcha')" />
  1. 运行项目,访问 View 即可生成图形验证码。

注意:示例中使用了 Session 来存储验证码,需要在 Startup.cs 文件中添加以下代码:

services.AddSession();

并在 Configure 方法中添加以下代码:

app.UseSession();
Net6 WebApi 项目生成图形验证码示例

原文地址: https://www.cveoy.top/t/topic/lwNO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录