ASP. NET 5 adventure (8): Using Middleware and TagHelper to implement Captcha and taghelpercaptcha in MVC 6
(This article is also published in my public account "dotNET daily excellent article". Welcome to the QR code on the right to follow it .)
Question: Due to ASP. NET 5 and MVC 6 are all new Web development platforms of Microsoft. Some existing verification code libraries cannot be used directly. Therefore, I have implemented a simple verification code library named CaptchaMVC6.
CaptchaMVC6 has been open-source to GitHub (examples are provided for your reference). You can access the project page by reading the original article.
CaptchaMVC6 although some of the Core algorithms are not essentially different from the existing verification code library, the entire encapsulation method fully utilizes the new features of ASP. NET 5 and MVC 6:
- Use ASP. NET 5 middleware to render Verification Code images. In the past, HttpHandler, HttpModule, or ASP. net mvc controllers were commonly used. For relevant code, see CaptchaMiddleware. cs, CaptchaMiddlewareExtensions. cs.
- Simplify the processing in the View Based on TagHelper. For example, to display a verification code image, the common practice is to specify an address and directly set the server Verification Code Image Rendering address for src In the img element. With TagHelper, you only need to add a custom attribute to the img element. In addition, you can also use TagHelper to control whether or not to display the verification code (see below ). For more information about the code, see CaptchaTagHelper. cs.
- Based on the dependency injection mechanism of ASP. NET 5, you can easily replace the verification code generation algorithm (of course, I also provide a simple default algorithm ). For relevant code, see CaptchaServiceCollectionExtensions. cs, defacodecodegenerator. cs, defagraphgraphicgenerator. cs.
In addition to the above features, CaptchaMVC6 has two additional features:
In the example, I demonstrated two use cases:
Note that because CaptchaMVC6 uses the System. Drawing assembly, it cannot run on dnxcore50, that is, cross-platform. In addition, this is an initial version, and there are still many improvements to be made. In addition, I will provide the Nuget package as soon as possible for your convenience.
Project address: https://github.com/heavenwing/CaptchaMVC6