c#页面验证类DataValidate代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.UI.WebControls;
using System.Text.RegularExpressions;

namespace Tools.Common
{
    /// <summary>
    /// 页面验证类
    /// </summary>
    public class DataValidate
    {
        private static Regex RegPhone = new Regex(@"^(1\d{10})|(\d{3,4}[-]\d{6,8})$");

        /// <summary>
        /// 纯数字,无正负号
        /// </summary>
        private static Regex RegNumber = new Regex("^[0-9]+$");
        /// <summary>
        /// 纯数字,可能有正负号
        /// </summary>
        private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
        /// <summary>
        /// 可能有有小数点的数字
        /// </summary>
        private static Regex RegDecimal = new Regex(@"^(\d+[.]\d+)|(\d+)$");
        /// <summary>
        /// 可能有小数点,也有可能有正负号的数字
        /// </summary>
        private static Regex RegDecimalSign = new Regex(@"^[+-]?((\d+[.]\d+)|(\d+))$"); //等价于^[+-]?\d+[.]?\d+$
        /// <summary>
        /// Email地址
        /// </summary>
        private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info|com.cn)$");
        /// <summary>
        /// 是否有中文
        /// </summary>
        private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");

        /// <summary>
        /// 是否为int数据
        /// </summary>
        private static Regex RegInt = new Regex(@"^(-){0,1}\d+$");

        #region 是否是中国的电话号码
        /// <summary>
        /// 是否是中国的电话号码
        /// </summary>
        /// <param name="inputData">输入的字符串</param>
        /// <returns></returns>
        public static bool IsPhone(string inputData)
        {

            Match m = RegPhone.Match(inputData);

            return m.Success;

        }
        #endregion

        #region 获取Request请求字符串的键值
        /// <summary>
        /// 获取Request请求字符串的键值
        /// </summary>
        /// <param name="req">Request</param>
        /// <param name="inputKey">Request的键值</param>
        /// <returns>返回Request请求字符串</returns>
        public static string GetRequest(HttpRequest req, string inputKey)
        {
            string retVal = string.Empty;
            if (inputKey != null && inputKey != string.Empty)
            {
                retVal = req.QueryString[inputKey];
                if (null == retVal) retVal = req.Form[inputKey];
            }

            if (retVal == null) retVal = string.Empty;
            return retVal;
        }
        #endregion

        #region 是否数字字符串
        /// <summary>
        /// 是否数字字符串
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsNumber(string inputData)
        {
            Match m = RegNumber.Match(inputData);

            return m.Success;

        }

        /// <summary>
        /// 是否数字字符串 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>

        public static bool IsNumberSign(string inputData)
        {
            Match m = RegNumberSign.Match(inputData);

            return m.Success;

        }
        #endregion

        #region 是否是浮点数
        /// <summary>
        /// 是否是浮点数
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsDecimal(string inputData)
        {
            decimal d1;
            return decimal.TryParse(inputData, out d1);
        }

        /// <summary>
        /// 是否是浮点数 可带正负号
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>

        public static bool IsDecimalSign(string inputData)
        {
            Match m = RegDecimalSign.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 检测是否有中文字符
        /// <summary>
        /// 检测是否有中文字符
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsHasCHZN(string inputData)
        {
            Match m = RegCHZN.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 是否是邮件地址
        /// <summary>
        /// 是否是邮件地址
        /// </summary>
        /// <param name="inputData">输入字符串</param>
        /// <returns></returns>
        public static bool IsEmail(string inputData)
        {
            Match m = RegEmail.Match(inputData);
            return m.Success;
        }
        #endregion

        #region 字符串编码HtmlEncode
        /// <summary>
        /// 字符串编码HtmlEncode
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static string HtmlEncode(string inputData)
        {
            return HttpUtility.HtmlEncode(inputData);

        }
        #endregion

        #region 设置Label显示Encode的字符串
        /// <summary>
        /// 设置Label显示Encode的字符串
        /// </summary>
        /// <param name="lbl"></param>
        /// <param name="txtInput"></param>
        public static void SetLabel(Label lbl, string txtInput)
        {
            lbl.Text = HtmlEncode(txtInput);
        }
        #endregion

        #region 字符串清理
        /// <summary>
        /// 字符串清理
        /// </summary>
        /// <param name="inputString">输入的字符串</param>
        /// <param name="maxLength">保留的长度</param>
        /// <returns></returns>
        public static string ClearText(string inputString, int maxLength)
        {

            StringBuilder retVal = new StringBuilder();
            // 检查是否为空
            if ((inputString != null) && (inputString != String.Empty))
            {
                inputString = inputString.Trim();
                //检查长度
                if (inputString.Length > maxLength)
                {
                    inputString = inputString.Substring(0, maxLength);
                }

                //替换危险字符
                for (int i = 0; i < inputString.Length; i++)
                {
                    switch (inputString[i])
                    {
                        case '"':
                            retVal.Append(""");
                            break;

                        case '<':

                            retVal.Append("<");
                            break;
                        case '>':
                            retVal.Append(">");
                            break;
                        default:
                            retVal.Append(inputString[i]);
                            break;
                    }
                }
                retVal.Replace("'", " ");// 替换单引号

            }

            return retVal.ToString();

        }
        #endregion

        #region  HTML Encode/Decode
        /// <summary>
        /// 转换成 HTML code
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Encode(string str)
        {
            str = str.Replace("&", "&");
            str = str.Replace("'", "''");
            str = str.Replace("\"", """);
            str = str.Replace(" ", " ");
            str = str.Replace("<", "<");
            str = str.Replace(">", ">");
            str = str.Replace("\n", "<br>");
            return str;
        }

        /// <summary>
        ///解析html成 普通文本
        /// </summary>
        /// <param name="str">string</param>
        /// <returns>string</returns>
        public static string Decode(string str)
        {
            str = str.Replace("<br>", "\n");
            str = str.Replace(">", ">");
            str = str.Replace("<", "<");
            str = str.Replace(" ", " ");
            str = str.Replace(""", "\"");
            return str;
        }
        #endregion

        #region 清理字符串
        /// <summary>
        /// 清理字符串
        /// </summary>
        /// <param name="sqlText"></param>
        /// <returns></returns>
        public static string SqlTextClear(string sqlText)
        {
            if (sqlText == null)
            {
                return null;
            }
            if (sqlText == "")
            {
                return "";
            }
            sqlText = sqlText.Replace(",", "");//去除,
            sqlText = sqlText.Replace("<", "");//去除<
            sqlText = sqlText.Replace(">", "");//去除>
            sqlText = sqlText.Replace("--", "");//去除--
            sqlText = sqlText.Replace("'", "");//去除'
            sqlText = sqlText.Replace("\"", "");//去除"
            sqlText = sqlText.Replace("=", "");//去除=
            sqlText = sqlText.Replace("%", "");//去除%
            sqlText = sqlText.Replace(" ", "");//去除空格
            return sqlText;
        }
        #endregion

        #region 是否由特定字符组成
        /// <summary>
        /// 是否由特定字符组成
        /// </summary>
        /// <param name="strInput">要检测的字符串</param>
        /// <returns></returns>
        public static bool isContainSameChar(string strInput)
        {

            string charInput = string.Empty;

            if (!string.IsNullOrEmpty(strInput))
            {

                charInput = strInput.Substring(0, 1);

            }

            return isContainSameChar(strInput, charInput);

        }
        /// <summary>
        /// 是否由特定字符组成2
        /// </summary>
        /// <param name="strInput">要检测的字符串</param>
        /// <param name="charInput">是否包含的字符</param>
        /// <returns></returns>
        public static bool isContainSameChar(string strInput, string charInput)
        {

            if (string.IsNullOrEmpty(charInput))
            {
                return false;
            }
            else
            {
                Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
                //Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
                Match m = RegNumber.Match(strInput);
                return m.Success;
            }
        }
        #endregion

        #region 检查输入的是不是某些定义好的字符
        /// <summary>
        /// 检查输入的是不是某些定义好的字符:用于密码输入的安全检查
        /// </summary>
        /// <param name="strInput">要检测的字符串</param>
        /// <returns></returns>
        public static bool isContainSpecChar(string strInput)
        {
            string[] list = new string[] { "123456", "654321" };
            bool result = new bool();
            for (int i = 0; i < list.Length; i++)
            {
                if (strInput == list[i])
                {
                    result = true;
                    break;
                }
            }
            return result;
        }
        #endregion

        #region 是不是int范围数据
        /// <summary>
        /// 是不是int范围数据
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsInt(string inputData)
        {

            if (RegInt.Match(inputData).Success)
            {
                if ((long.Parse(inputData) > 0x7fffffffL) || (long.Parse(inputData) < -2147483648L))
                {
                    return false;
                }
                return true;
            }
            return false;
        }
        #endregion

        #region 是否是邮编号码
        /// <summary>
        /// 是否是邮编号码
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsPostCode(string inputData)
        {
            return Regex.IsMatch(inputData, @"^\d{6}$", RegexOptions.IgnoreCase);
        }
        #endregion

        #region 是不是字母、数字、下划线的组合
        /// <summary>
        /// 是不是字母、数字、下划线的组合
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsNormalChar(string inputData)
        {
            return Regex.IsMatch(inputData, @"[\w\d_]+", RegexOptions.IgnoreCase);
        } 
        #endregion

        #region 是不是日期类型
        /// <summary>
        /// 是不是日期类型
        /// </summary>
        /// <param name="inputData"></param>
        /// <returns></returns>
        public static bool IsDataTime(string inputData)
        {
            DateTime dt1;
            return DateTime.TryParse(inputData, out dt1);
        }  
        #endregion

    }
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
一款功能仿百度贴吧的.Net贴吧程序系统。基于VS 2008开发。数据库为MS SQL 2000/2005.系统仿百度贴吧简洁友好界面,支持主题帖静态生成。具备所有贴吧功能: 1、用户注册; 2、用户发贴,匿名用户发贴,图片发布等; 3、会员管理,锁定、屏蔽特定用户名; 4、吧主管理贴吧,贴吧锁定,单贴锁定 5、管理员后台管理; 6、多种形式站点广告管理; ...... 系统运行环境:Microsoft .NET Framework 2.0 + MS SQL 2000/2005 数据库Sql文件,执行即可。修改web.config数据库连接为您在使用的数据库名称。bin文件夹放置站点根目录! │ Ac.aspx 登陆 注册 退出 过程处理 │ Ac_T.aspx 贴子 置顶 精华 公告 删除 锁定 删除回复 处理 │ Admin_login.aspx 管理登陆 │ B.aspx 浏览贴子 详细内容 │ D.aspx 用户登陆 │ Default.aspx │ ErrorMsg.aspx 错误信息提示 │ F.aspx 所有贴子列表(主题) │ G.aspx 个人中心 │ index.aspx 首页 │ L.aspx 贴吧列表 │ PrecompiledApp.config │ R.aspx 用户注册 │ S.aspx 建立关键字的吧 │ T.aspx 主题列表 │ Tops.ascx 公共头部 │ U.aspx 用户信息 │ Url.aspx 图片展示页 │ ValidateNumber.aspx 验证码页 │ web.config │ ├─Admin │ Admin_Ad.aspx 广告 │ Admin_admin.aspx 管理员 │ Admin_board.aspx 贴吧 │ Admin_class.aspx 别 │ Admin_data.aspx │ Admin_index.aspx 首页 │ Admin_link.aspx 友情连接 │ Admin_system.aspx 系统设置 │ Admin_User.aspx 会员管理 │ left.aspx │ Style.css │ welcome.htm │ ├─bin │ ClassLibrary.dll │ YHbar_BLL.dll │ YHbar_DAL.dll │ YHbar_Model.dll │ YHbar_Web.dll │ ├─CSS │ B.css │ L.css │ T.css │ └─JS commonAboutJoin.js
About the Book<br/><br/>Real-world developer training for results on the job—and on the exam.<br/><br/>Build real-world programming skills—and prepare for MCP Exams 70-306 and 70-316—with this official Microsoft study guide. Work at your own pace through the lessons and hands-on exercises to learn how to build Windows-based applications using Visual Basic .NET and Visual C# .NET. Then extend your expertise through additional skill-building exercises. As you gain practical experience with essential development tasks, you’re also preparing for MCAD or MCSD certification for Microsoft .NET.<br/><br/>Learn how to: <br/>•Create the user interface, add controls, and validate user input<br/>•Use OOP techniques, including encapsulation and method overloading<br/>•Build custom controls and .NET assemblies<br/>•Access and modify data using XML, Microsoft ADO.NET, and SQL syntax<br/>•Implement print support, online help, and accessibility and globalization features<br/>•Test and debug coding errors<br/>•Configure and help secure an application <br/>•Deploy applications via removable media, the Web, or a network<br/>•Maintain and optimize application performance<br/><br/>Your kit includes:<br/>•NEW—60-day evaluation version of Microsoft Visual Studio® .NET 2003 Professional Edition on DVD<br/>•Comprehensive self-paced study guide that maps to the objectives of the final exams<br/>•NEW—Expanded coverage of ADO.NET, SQL syntax, Windows Forms, debugging, and security<br/>•NEW—150 challenging practice questions on CD. Test yourself by exam (70-306 or 70-316) or by individual objective(s). Choose the number of questions and timed or untimed mode. You get automated scoring and detailed explanations for both correct and incorrect answers.<br/>•Learn-by-doing exercises for skills you can apply to the job<br/>•Side-by-side code examples and labs for Visual C# .NET and Visual Basic .NET<br/>•Fully searchable eBook
系统设计之公共库 ?Data Class Name File Function SQL访问基础 SqlHelper.cs 执行带参数SQL,非带参数SQL,存储过程等语句 Access操作辅助 JetAccess.cs Access的新建,压缩,加密等数据库文件操作 Oledb操作辅助 OleDbHelper.cs 使用OleDb数据源执行SQL语句 ?Common Class Name File Function 执行命令 CmdUtil.cs 执行各命令;如:cmd.exe 公历/农历 CNDate.cs 公历、农历、星座、气节等相关转换 日期格式处理 DateUtil.cs 日期格式、闰月、计算当月天数等转换 文件实用 FileUtil.cs 读取、备份、创建等文件操作 上传 HtmlInputFileControl.cs 单个文件上传,控制文件格式大小 图片处理 ImageUtil.cs 缩略图、水印等操作 授权 Licence.cs 生成授权码,验政授权码 链接辅助 ListBuilder.cs 动态化url,target,css等属性 分页 PageListUtil.cs 分页使用 反射辅助 ReflectHelper.cs 获取程序集嵌位图,文本等资源或形式 浏览器辅助 Request.cs Get,post请求判断,url信息抓取,跨站处理等 序列化功能辅助 SerializeHelper.cs 二进制,XmlDocument系列化及获取对象 Session封装 SessionAdapter.cs 对Session进行封装 Smtp邮件辅助 SmtpMail.cs 配置Smtp邮件发送及HTM邮件传送 字符串实用 StringUtil.cs 处理字符串分割,转换,嵌入等方法 型转换 TypeParse.cs 各种型互相转换,如int string bool等 用户实用 User.cs 登陆,退出时候身份加密或解除方式 验证 ValidateImage.cs 图片验证验证实用 ValidateUtils.cs 数据型,字符串功能,IP,日期,SQL注入等验证方法 XML处理基 XMLHelper.cs 查看,删除,增加,修改XML数据与节点 数据出库处理 GetSafeData.cs 处理数据库各型出库的异常 常用方法 GeneralHelper.cs 开发常用方法,由于多个存在,项目开发新建单独调用 ?Web Class Name File Function 网页界面功能 WebUI.cs 控件,文本的界面处理功能 UBB代码辅助 UBB.cs UBB代码转换 客户端代码功能 JScript.cs 提供向页面输出客户端代码实现特殊功能的方法 客户端代码精简 JavaScriptMinifier.cs 转换原始Js内容的精简版本 HTML格式辅助 HtmlUtils.cs 处理HTML,脚本的特殊字符或过滤 数据压缩 GZipHandler.cs 对传输的数据进行压缩 ?DLL Dll Name AjaxPro.dll AspNetPager.dll FreeTextBox.dll URLRewriter.dll Function Ajax控件 分页控件 在线编辑器控件 URL重写控件 本库为转发
dbfC#DataGridView中的常用技巧 只列出技巧部分,后面会有补充 0(最基本的技巧). 获取某列中的某行(某单元格)中的内容 this.currentposition = this.dataGridView1.BindingContext [this.dataGridView1.DataSource, this.dataGridView1.DataMember].Position; bookContent = this.database.dataSet.Tables[0].Rows [this.currentposition][21].ToString().Trim(); MessageBox.Show(bookContent); 1、自定义列 //定义列宽 this.dataGridView1.Columns[0].Width = 80; this.dataGridView1.Columns[1].Width = 80; this.dataGridView1.Columns[2].Width = 180; this.dataGridView1.Columns[3].Width = 120; this.dataGridView1.Columns[4].Width = 120; Customize Cells and Columns in the Windows Forms DataGridView Control by Extending Their Behavior and Appearance Host Controls in Windows Forms DataGridView Cells 继承 DataGridViewTextBoxCell 生成新的Cell,然后再继承 DataGridViewColumn 生成新的Column,并指定 CellTemplate为新的Cell。新生成的Column便可以增加到DataGridView中去。 2、自动适应列宽 Programmatically Resize Cells to Fit Content in the Windows Forms DataGridView Control Samples: DataGridView.AutoSizeColumns( DataGridViewAutoSizeColumnCriteria.HeaderAndDisplayedRows); DataGridView.AutoSizeColumn( DataGridViewAutoSizeColumnCriteria.HeaderOnly, 2, false); DataGridView.AutoSizeRow( DataGridViewAutoSizeRowCriteria.Columns, 2, false); DataGridView.AutoSizeRows( DataGridViewAutoSizeRowCriteria.HeaderAndColumns, 0, dataGridView1.Rows.Count, false); 3、可以绑定并显示对象 Bind Objects to Windows Forms DataGridView Controls 4、可以改变表格线条风格 Change the Border and Gridline Styles in the Windows Forms DataGridView Control Samples: this.dataGridView1.GridColor = Color.BlueViolet; this.dataGridView1.BorderStyle = BorderStyle.Fixed3D; this.dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None; this.dataGridView1.RowHeadersBorderStyle = DataGridVie
以下是一个 C# WebAPI 中实现 Header 验证的示例代码: ```csharp public class HeaderAuthenticationFilter : IAuthenticationFilter { private readonly string apiKey = "your_api_key_here"; public bool AllowMultiple => false; public async Task AuthenticateAsync(HttpAuthenticationContext context, CancellationToken cancellationToken) { // 获取请求头的 Authorization 字段 var authHeader = context.Request.Headers.Authorization; // 如果 Authorization 字段不存在或不是 Bearer 形式的 Token,则返回未授权的错误 if (authHeader == null || !authHeader.Scheme.Equals("Bearer", StringComparison.OrdinalIgnoreCase)) { context.ErrorResult = new AuthenticationFailureResult("Unauthorized", context.Request); return; } // 获取 Token var token = authHeader.Parameter; // 验证 Token 是否正确 if (string.IsNullOrWhiteSpace(token) || !token.Equals(apiKey)) { context.ErrorResult = new AuthenticationFailureResult("Unauthorized", context.Request); return; } // 设置用户身份验证信息 var identity = new GenericIdentity("user"); context.Principal = new GenericPrincipal(identity, new string[] { }); } public Task ChallengeAsync(HttpAuthenticationChallengeContext context, CancellationToken cancellationToken) { return Task.FromResult(0); } } public class AuthenticationFailureResult : IHttpActionResult { public string ReasonPhrase { get; private set; } public HttpRequestMessage Request { get; private set; } public AuthenticationFailureResult(string reasonPhrase, HttpRequestMessage request) { ReasonPhrase = reasonPhrase; Request = request; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; response.ReasonPhrase = ReasonPhrase; return Task.FromResult(response); } } ``` 在上述代码中,我们创建了一个名为 `HeaderAuthenticationFilter` 的,该实现了 `IAuthenticationFilter` 接口,用于在 WebAPI 的管道中进行身份验证。我们在 `AuthenticateAsync` 方法中进行身份验证,如果验证失败,则设置 `ErrorResult` 属性返回未授权的错误。如果验证成功,则设置 `Principal` 属性为一个包含用户信息的 `IPrincipal` 对象。最后,我们创建了一个名为 `AuthenticationFailureResult` 的,该实现了 `IHttpActionResult` 接口,用于返回错误响应。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值