


asp.net creates a bitmap to generate a verification image class (verification code class)
Jan 13, 2017 pm 03:26 PMCode:
public void ProcessRequest(HttpContext context) { context.Response.ContentType = "image/jpeg"; //創(chuàng)建位圖,并且給指定邊框的寬高 using (Image img=new Bitmap(80,25)) { //創(chuàng)建畫家對象,在img對象畫字符串 using (Graphics g=Graphics.FromImage(img)) { //設(shè)置位圖的背景顏色,默認(rèn)是黑色 g.Clear(Color.White); //設(shè)置驗(yàn)證碼的寬高, img.Width-1, img.Height-1主要是背景顏色覆蓋了邊框線 g.DrawRectangle(Pens.Black, 0, 0, img.Width-1, img.Height-1); //傳100個噪點(diǎn),傳畫家對象,位圖對象 DrawPoint(100, g, img); //畫4個驗(yàn)證碼的字符串 string vcode=GetCode(4);//vcode這里可以賦值給Cookie g.DrawString(vcode, new Font("Arial", 14, FontStyle.Strikeout | FontStyle.Strikeout), // FontStyle字體的樣式,多個樣式,需要|線 Brushes.Black, new RectangleF(r.Next(20), r.Next(7), img.Width, img.Height)); img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);//保存驗(yàn)證碼對象,指定是Jpeg格式 } } } //畫噪點(diǎn)方法 void DrawPoint(int point,Graphics g,Image img) { for (int i = 0; i < point; i++) { int x = r.Next(img.Width); int y = r.Next(img.Width); g.DrawLine(Pens.Red, new Point(x, y), new Point(x+2, y+2)); } } //隨機(jī)數(shù) Random r = new Random(); //畫字符創(chuàng) string GetCode(int point) { string txtStr = "ASF2345WE5R9F3HMBCZ455K";//這里的string字符串將會轉(zhuǎn)成 char數(shù)組,阿拉伯?dāng)?shù)字1和小寫字母l最好別寫在里面,會搞胡亂。 char[] charArr = txtStr.ToArray(); int num = 0; string code = ""; for (int i = 0; i <point; i++) { num = r.Next(charArr.Length); code +=charArr[num]; } return code; }
For more asp.net creation bitmap generation verification image class (verification code class) related articles, please pay attention to the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The core of designing immutable objects and data structures in C# is to ensure that the state of the object is not modified after creation, thereby improving thread safety and reducing bugs caused by state changes. 1. Use readonly fields and cooperate with constructor initialization to ensure that the fields are assigned only during construction, as shown in the Person class; 2. Encapsulate the collection type, use immutable collection interfaces such as ReadOnlyCollection or ImmutableList to prevent external modification of internal collections; 3. Use record to simplify the definition of immutable model, and generate read-only attributes and constructors by default, suitable for data modeling; 4. It is recommended to use System.Collections.Imm when creating immutable collection operations.

Generic constraints are used to restrict type parameters to ensure specific behavior or inheritance relationships, while covariation allows subtype conversion. For example, whereT:IComparable ensures that T is comparable; covariation such as IEnumerable allows IEnumerable to be converted to IEnumerable, but it is only read and cannot be modified. Common constraints include class, struct, new(), base class and interface, and multiple constraints are separated by commas; covariation requires the out keyword and is only applicable to interfaces and delegates, which is different from inverter (in keyword). Note that covariance does not support classes, cannot be converted at will, and constraints affect flexibility.

The key to writing C# code well is maintainability and testability. Reasonably divide responsibilities, follow the single responsibility principle (SRP), and take data access, business logic and request processing by Repository, Service and Controller respectively to improve structural clarity and testing efficiency. Multi-purpose interface and dependency injection (DI) facilitate replacement implementation, extension of functions and simulation testing. Unit testing should isolate external dependencies and use Mock tools to verify logic to ensure fast and stable execution. Standardize naming and splitting small functions to improve readability and maintenance efficiency. Adhering to the principles of clear structure, clear responsibilities and test-friendly can significantly improve development efficiency and code quality.

Create custom middleware in ASP.NETCore, which can be implemented by writing classes and registering. 1. Create a class containing the InvokeAsync method, handle HttpContext and RequestDelegatenext; 2. Register with UseMiddleware in Program.cs. Middleware is suitable for general operations such as logging, performance monitoring, exception handling, etc. Unlike MVC filters, it acts on the entire application and does not rely on the controller. Rational use of middleware can improve structural flexibility, but should avoid affecting performance.

The correct way to use dependency injection in C# projects is as follows: 1. Understand the core idea of DI is to not create objects by yourself, but to receive dependencies through constructors to achieve loose coupling; 2. When registering services in ASP.NETCore, you need to clarify the life cycle: Transient, Scoped, Singleton, and choose according to business needs; 3. It is recommended to use constructor injection, and the framework will automatically parse dependencies, which are suitable for controllers and services; 4. Built-in containers can be used in small projects, and third-party containers such as Autofac can be introduced in complex scenarios, and custom service registration and configuration reading are supported. Mastering these key points can help improve the testability, maintainability and scalability of your code.

Fluent interface is a design method that improves code readability and expressivity through chain calls. The core of it is that each method returns the current object, so that multiple operations can be called continuously, such as varresult=newStringBuilder().Append("Hello").Append("").Append("World"). When implementing, you need to combine the extension method and the design pattern that returns this, such as defining the FluentString class and returning this in its method, and creating an initial instance through the extension method. Common application scenarios include building configurators (such as verification rules), checking

Common problems with async and await in C# include: 1. Incorrect use of .Result or .Wait() causes deadlock; 2. Ignoring ConfigureAwait(false) causes context dependencies; 3. Abuse of asyncvoid causes control missing; 4. Serial await affects concurrency performance. The correct way is: 1. The asynchronous method should be asynchronous all the way to avoid synchronization blocking; 2. The use of ConfigureAwait(false) in the class library is used to deviate from the context; 3. Only use asyncvoid in event processing; 4. Concurrent tasks need to be started first and then await to improve efficiency. Understanding the mechanism and standardizing the use of asynchronous code that avoids writing substantial blockage.

CachinginC#applicationscanbeeffectivelyimplementedusingin-memorycaching,Redisfordistributedscenarios,andproperinvalidationstrategies.UseIMemoryCacheforfastlocalcachingwithexpirationpolicies,RedisviaStackExchange.Redisforsharedorlarge-scalecaching,and
