1、必须填写[Required(ErrorMessage = "纸张名称不能为空")] public string Name { get; set; }2、长度限制//至多n位： [StringLength(50, ErrorMessage = "最多50个字符")] public string Name { get; set; } //要求至少n位： [StringLength(50, MinimumLength=10, ErrorMessage = "10~50个字符")] public string Name { get; set; }3、正则验证[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", ErrorMessage = "格式错误")] public string Email { get; set; }4、数字范围//整数 [Range(1,120, ErrorMessage = "范围1~120")] public int Age { get; set; } //小数 [Range(typeof(decimal), "0.00", "49.99", ErrorMessage = "范围0~49.99")] public decimal Price { get; set; }5、比较验证//新密码 public string NewPassword{ get; set; } //确认密码 [Compare("NewPassword",ErrorMessage = "确认密码与新密码不一致")] public string ConfirmPassword{ get; set; }7、常用正则表达式数字："^[0-9]*$"。 n位的数字："^\d{n}$"。 至少n位的数字："^\d{n,}$"。 m~n位的数字：。"^\d{m,n}$" 零和非零开头的数字："^(0|[1-9][0-9]*)$"。 有两位小数的正实数："^[0-9]+(.[0-9]{2})?$"。 有1~3位小数的正实数："^[0-9]+(.[0-9]{1,3})?$"。 非零的正整数："^\+?[1-9][0-9]*$"。 非零的负整数："^\-[1-9][]0-9"*$。 长度为3的字符："^.{3}$"。 由26个英文字母组成的字符串："^[A-Za-z]+$"。 由26个大写英文字母组成的字符串："^[A-Z]+$"。 由26个小写英文字母组成的字符串："^[a-z]+$"。 由数字和26个英文字母组成的字符串："^[A-Za-z0-9]+$"。 由数字、26个英文字母或者下划线组成的字符串："^\w+$"。 验证用户密码："^[a-zA-Z]\w{5,17}$"正确格式为：以字母开头，长度在6~18之间，只能包含字符、数字和下划线。 验证是否含有^%&’,;=?$\"等字符："[^%&’,;=?$\x22]+"。 只能输入汉字："^[\u4e00-\u9fa5]{0,}$" 验证Email地址："^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"。 验证InternetURL："^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$"。 验证电话号码："^(\(\d{3,4}-)|\d{3.4}-)?\d{7,8}$"正确格式为："XXX-XXXXXXX"、"XXXX- XXXXXXXX"、"XXX-XXXXXXX"、"XXX-XXXXXXXX"、"XXXXXXX"和"XXXXXXXX"。 验证身份证号(15位或18位数字)："^\d{15}|\d{18}$"。 验证一年的12个月："^(0?[1-9]|1[0-2])$"正确格式为："01"～"09"和"1"～"12"。 验证一个月的31天："^((0?[1-9])|((1|2)[0-9])|30|31)$"正确格式为;"01"～"09"和"1"～"31"。
C#调用WPS转换Word、Excel、PPT文件为PDF，耗时稍微长一点，但是文件转换格式不存在问题。需要安装WPSusing System; using Excel; using PowerPoint; using Word; namespace SharePint.Code { public class FileTransform { /// /// Word转PDF /// /// word文件地址 /// 保存PDF地址 /// <returns></returns> public static bool WordToPdf(string pWordFile, string pSavePdf) { var type = Type.GetTypeFromProgID("KWps.Application"); dynamic wps = Activator.CreateInstance(type); try { var doc = wps.Documents.Open(pWordFile, Visible: false); doc.ExportAsFixedFormat(pSavePdf, WdExportFormat.wdExportFormatPDF); doc.Close(); } catch (Exception e) { return false; } finally { wps.Quit(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return true; } /// /// Excel转PDF /// /// Excel文件地址 /// 保存PDF地址 /// <returns></returns> public static bool ExcelToPdf(string pExcelFile, string pSavePdf) { var type = Type.GetTypeFromProgID("KET.Application"); dynamic wps = Activator.CreateInstance(type); try { var targetType = XlFixedFormatType.xlTypePDF; var missing = Type.Missing; var doc = wps.Application.Workbooks.Open(pExcelFile, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing); doc.ExportAsFixedFormat(targetType, pSavePdf, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing); doc.Close(); } catch (Exception e) { return false; } finally { wps.Quit(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return true; } /// /// PPT转PDF /// /// PPT文件地址 /// 保存PDF地址 /// <returns></returns> public static bool PptToPdf(string pPptFile, string pSavePdf) { var type = Type.GetTypeFromProgID("KWPP.Application"); dynamic wps = Activator.CreateInstance(type); try { var doc = wps.Presentations.Open(pPptFile, MsoTriState.msoCTrue, MsoTriState.msoCTrue, MsoTriState.msoCTrue); doc.SaveAs(pSavePdf, PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue); doc.Close(); } catch (Exception e) { return false; } finally { wps.Quit(); GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); } return true; } } } ``
刚开始使用 Entity Framework 的时候，由于没有静下心来认真理清关系，走了一些"痛不欲生"的弯路。而我们目前开发的项目都在使用 Entity Framework，为了避免其他人再经历"痛不欲生"的弯路。于是下定决心边“理清关系”边“写博客”。而写博客可以逼着自己把问题完整地解决，避免半途而废。当写出这些文章，自己不知不觉对问题有了更深的理解。1. 一对一关系（one-to-one）a) 单向一对一类图：数据库表结构：Entity Framework中实体关系的定义：modelBuilder.Entity<BlogSite>() .HasRequired(b => b.BlogUser) .WithMany() .HasForeignKey(b => b.UserID);b) 双向一对一类图：数据库表结构：Entity Framework中实体关系的定义：modelBuilder.Entity<BlogSite>() .HasRequired(b => b.BlogUser) .WithMany() .HasForeignKey(b => b.UserID); modelBuilder.Entity<BlogUser>() .HasRequired(u => u.BlogSite) .WithMany() .HasForeignKey(u => u.BlogID);2. 一对多关系（one-to-many）类图：数据库表结构：Entity Framework中实体关系的定义：modelBuilder.Entity<BlogSite>() .HasMany(b => b.BlogPosts) .WithRequired(p => p.BlogSite);3. 多对多关系（many-to-many）类图：数据库表结构：Entity Framework中实体关系的定义：modelBuilder.Entity<BlogSite>() .HasMany(b => b.Categories) .WithMany(c => c.BlogPosts) .Map ( m => { m.MapLeftKey("BlogPostID"); m.MapRightKey("CategoryID"); m.ToTable("BlogPost_Category"); } );
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Ell.Web.Code.Edit; using Newtonsoft.Json; namespace Ell.Web.Controllers { public class EditController : Controller { public void Index() { HttpContext context = System.Web.HttpContext.Current; Handler action = null; switch ( context.Request["action"] ) { case "config": action = new ConfigHandler( context ); break; case "uploadimage": action = new UploadHandler( context, new UploadConfig() { AllowExtensions = Config.GetStringList( "imageAllowFiles" ), PathFormat = Config.GetString( "imagePathFormat" ), SizeLimit = Config.Getint( "imageMaxSize" ), UploadFieldName = Config.GetString( "imageFieldName" ) } ); break; case "uploadscrawl": action = new UploadHandler( context, new UploadConfig() { AllowExtensions = new string[] { ".png" }, PathFormat = Config.GetString( "scrawlPathFormat" ), SizeLimit = Config.Getint( "scrawlMaxSize" ), UploadFieldName = Config.GetString( "scrawlFieldName" ), Base64 = true, Base64Filename = "scrawl.png" } ); break; case "uploadvideo": action = new UploadHandler( context, new UploadConfig() { AllowExtensions = Config.GetStringList( "videoAllowFiles" ), PathFormat = Config.GetString( "videoPathFormat" ), SizeLimit = Config.Getint( "videoMaxSize" ), UploadFieldName = Config.GetString( "videoFieldName" ) } ); break; case "uploadfile": action = new UploadHandler( context, new UploadConfig() { AllowExtensions = Config.GetStringList( "fileAllowFiles" ), PathFormat = Config.GetString( "filePathFormat" ), SizeLimit = Config.Getint( "fileMaxSize" ), UploadFieldName = Config.GetString( "fileFieldName" ) } ); break; case "listimage": action = new ListFileManager( context, Config.GetString( "imageManagerListPath" ), Config.GetStringList( "imageManagerAllowFiles" ) ); break; case "listfile": action = new ListFileManager( context, Config.GetString( "fileManagerListPath" ), Config.GetStringList( "fileManagerAllowFiles" ) ); break; case "catchimage": action = new CrawlerHandler( context ); break; default: action = new NotSupportedHandler( context ); break; } action.Process(); } public bool IsReusable => false; } }
1、配置文件项目文件添加Config文件夹，文件中添加对应xml文件<?xml version="1.0" encoding="utf-8" ?> <Config> <Partner>合作身份者ID，以2088开头由16位纯数字组成的字符串</Partner> <Seller>收款支付宝账号（邮箱地址）</Seller> <Key>交易安全检验码，由数字和字母组成的32位字符串</Key> </Config><?xml version="1.0" encoding="utf-8" ?> <Config> <MerId>2222222222</MerId> <Version>222222222</Version> <Encoding>2222222222</Encoding> <SignMethod>oeeeeq3iez</SignMethod> <TxnType>eebq3iez</TxnType> <TxnSubType>oeee3kstubbq3iez</TxnSubType> <BizType>ood1jmeeeq3iez</BizType> <ChannelType>ood1eeez</ChannelType> <AccessType>ood1eeee3iez</AccessType> <CurrencyCode>ood1jmcnez</CurrencyCode> <SignCertpwd>ood1jmcnhjee</SignCertpwd> <FrontTransUrl>ood1eetubbq3iez</FrontTransUrl> <CertPath>ood1jmcnhjm2aeee3iez</CertPath> </Config><?xml version="1.0" encoding="utf-8" ?> <Config> <AppId>wx09a1334d45f1</AppId> <AppSecret>100000000000000000000000000</AppSecret> <MchId>12312311</MchId> <Key>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</Key> </Config><?xml version="1.0" encoding="utf-8" ?> <Config> <AppId>wx09a1334d45f1</AppId> <AppSecret>100000000000000000000000000</AppSecret> <MchId>12312311</MchId> <Key>kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk</Key> </Config>2、发起支付protected void Page_Load(object sender, EventArgs e) { ////////////////////////////////////////////请求参数//////////////////////////////////////////// //必填，不能修改 //服务器异步通知页面路径 string notify_url = "http://商户网关地址/create_direct_pay_by_user-CSHARP-UTF-8/notify_url.aspx"; //需http://格式的完整路径，不能加?id=123这类自定义参数 //页面跳转同步通知页面路径 string return_url = "http://商户网关地址/create_direct_pay_by_user-CSHARP-UTF-8/return_url.aspx"; //需http://格式的完整路径，不能加?id=123这类自定义参数，不能写成http://localhost/ //商户订单号 string out_trade_no = DateTime.Now.ToString("xxxxxx00001"); //商户网站订单系统中唯一订单号，必填 //订单名称 string subject = "订单名称"; //必填 //付款金额 string total_fee = "0.01"; //必填 //订单描述 string body = "订单描述"; //商品展示地址 string show_url = "http://www.bollshow.com"; //需以http://开头的完整路径，例如：http://www.商户网址.com/myorder.html //支付宝防钓鱼时间戳 //string anti_phishing_key = Genius.Payment.Alipay.Submit.Query_timestamp(); //若要使用请调用类文件submit中的query_timestamp函数 //客户端的IP地址 string exter_invoke_ip = "221.0.0.1"; //支付宝二维码支付 string sHtmlText = Genius.Payment.Alipay.Utils.SendRequest(out_trade_no, subject, body, total_fee, notify_url, return_url, show_url); Response.Write(sHtmlText); //微信支付url string xx=Genius.Payment.WeiXinpay.QRUtils.SendRequest(out_trade_no,0.01m,"xxxxxxxxxx", notify_url, return_url); //银联支付 Genius.Payment.UnionPay.Utils.SendRequest(out_trade_no, 0.01m, "xxxxxxxxxx", notify_url, return_url); }3、支付同步回调using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Specialized; using System.Collections.Generic; /* * / * / 功能：页面跳转同步通知页面 * / 版本：3.3 * / 日期：2012-07-10 * / 说明： * / 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。 * / 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。 * / * / ///////////////////////页面功能说明/////////////////////// * / 该页面可在本机电脑测试 * / 可放入HTML等美化页面的代码、商户业务逻辑程序代码 * / 该页面可以使用ASP.NET开发工具调试，也可以使用写文本函数LogResult进行调试 * / */ public partial class return_url : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e ) { SortedDictionary<string, string> sPara = GetRequestGet(); if ( sPara.Count > 0 ) /* 判断是否有带返回参数 */ { Genius.Payment.Alipay.Notify aliNotify = new Genius.Payment.Alipay.Notify(); bool verifyResult = aliNotify.Verify( sPara, Request.QueryString["notify_id"], Request.QueryString["sign"] ); if ( verifyResult ) /* 验证成功 */ { /* * /////////////////////////////////////////////////////////////////////////////////////////////////////////// * 请在这里加上商户的业务逻辑程序代码 */ /* * ——请根据您的业务逻辑来编写程序（以下代码仅作参考）—— * 获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表 */ /* 商户订单号 */ string out_trade_no = Request.QueryString["out_trade_no"]; /* 支付宝交易号 */ string trade_no = Request.QueryString["trade_no"]; /* 交易状态 */ string trade_status = Request.QueryString["trade_status"]; if ( Request.QueryString["trade_status"] == "TRADE_FINISHED" || Request.QueryString["trade_status"] == "TRADE_SUCCESS" ) { /* * 判断该笔订单是否在商户网站中已经做过处理 * 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序 * 如果有做过处理，不执行商户的业务程序 */ }else { Response.Write( "trade_status=" + Request.QueryString["trade_status"] ); } /* 打印页面 */ Response.Write( "验证成功 " ); /* ——请根据您的业务逻辑来编写程序（以上代码仅作参考）—— */ /* /////////////////////////////////////////////////////////////////////////////////////////////////////////// */ }else { /* 验证失败 */ Response.Write( "验证失败" ); } }else { Response.Write( "无返回参数" ); } } /* * / * / 获取支付宝GET过来通知消息，并以“参数名=参数值”的形式组成数组 * / * / <returns>request回来的信息组成的数组</returns> */ public SortedDictionary<string, string> GetRequestGet() { int i = 0; SortedDictionary<string, string> sArray = new SortedDictionary<string, string>(); NameValueCollection coll; /* Load Form variables into NameValueCollection variable. */ coll = Request.QueryString; /* Get names of all forms into a string array. */ String[] requestItem = coll.AllKeys; for ( i = 0; i < requestItem.Length; i++ ) { sArray.Add( requestItem[i], Request.QueryString[requestItem[i]] ); } return(sArray); } }4、支付异步回调using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.Collections.Specialized; using System.Collections.Generic; /* * / * / 功能：服务器异步通知页面 * / 版本：3.3 * / 日期：2012-07-10 * / 说明： * / 以下代码只是为了方便商户测试而提供的样例代码，商户可以根据自己网站的需要，按照技术文档编写,并非一定要使用该代码。 * / 该代码仅供学习和研究支付宝接口使用，只是提供一个参考。 * / * / ///////////////////页面功能说明/////////////////// * / 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。 * / 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。 * / 该页面调试工具请使用写文本函数logResult。 * / 如果没有收到该页面返回的 success 信息，支付宝会在24小时内按一定的时间策略重发通知 * / */ public partial class notify_url : System.Web.UI.Page { protected void Page_Load( object sender, EventArgs e ) { SortedDictionary<string, string> sPara = GetRequestPost(); if ( sPara.Count > 0 ) /* 判断是否有带返回参数 */ { Genius.Payment.Alipay.Notify aliNotify = new Genius.Payment.Alipay.Notify(); bool verifyResult = aliNotify.Verify( sPara, Request.Form["notify_id"], Request.Form["sign"] ); if ( verifyResult ) /* 验证成功 */ { /* * /////////////////////////////////////////////////////////////////////////////////////////////////////////// * 请在这里加上商户的业务逻辑程序代码 */ /* * ——请根据您的业务逻辑来编写程序（以下代码仅作参考）—— * 获取支付宝的通知返回参数，可参考技术文档中服务器异步通知参数列表 */ /* 商户订单号 */ string out_trade_no = Request.Form["out_trade_no"]; /* 支付宝交易号 */ string trade_no = Request.Form["trade_no"]; /* 交易状态 */ string trade_status = Request.Form["trade_status"]; if ( Request.Form["trade_status"] == "TRADE_FINISHED" ) { /* * 判断该笔订单是否在商户网站中已经做过处理 * 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序 * 如果有做过处理，不执行商户的业务程序 * 注意： */ /* 退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知 */ }else if ( Request.Form["trade_status"] == "TRADE_SUCCESS" ) { /* * 判断该笔订单是否在商户网站中已经做过处理 * 如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序 * 如果有做过处理，不执行商户的业务程序 */ /* * 注意： * 付款完成后，支付宝系统发送该交易状态通知 */ }else { } /* ——请根据您的业务逻辑来编写程序（以上代码仅作参考）—— */ Response.Write( "success" ); /* 请不要修改或删除 */ /* /////////////////////////////////////////////////////////////////////////////////////////////////////////// */ }else { /* 验证失败 */ Response.Write( "fail" ); } }else { Response.Write( "无通知参数" ); } } /* * / * / 获取支付宝POST过来通知消息，并以“参数名=参数值”的形式组成数组 * / * / <returns>request回来的信息组成的数组</returns> */ public SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<string, string> sArray = new SortedDictionary<string, string>(); NameValueCollection coll; /* Load Form variables into NameValueCollection variable. */ coll = Request.Form; /* Get names of all forms into a string array. */ String[] requestItem = coll.AllKeys; for ( i = 0; i < requestItem.Length; i++ ) { sArray.Add( requestItem[i], Request.Form[requestItem[i]] ); } return(sArray); } }
1、Global.asax文件加入判断代码void Application_BeginRequest(object sender, EventArgs e) { string q = " 您的提交带有不合法参数,谢谢合作! 了解更多请点击:智汇科技 "; if (Request.Cookies != null) { if (WebSafe.CookieData()) { Response.Write("您提交的Cookie数据有恶意字符！"); Response.End(); } } if (Request.UrlReferrer != null) { if (WebSafe.referer()) { Response.Write("您提交的Referrer数据有恶意字符！"); Response.End(); } } if (Request.RequestType.ToUpper() == "POST") { if (WebSafe.PostData()) { Response.Write("您提交的Post数据有恶意字符！"); Response.End(); } } if (Request.RequestType.ToUpper() == "GET") { if (WebSafe.GetData()) { Response.Write("您提交的Get数据有恶意字符！"); Response.End(); } } }2、附请求过滤验证防恶意字符类库using System.Text.RegularExpressions; using System.Web; namespace Als.Utils.Net { public class WebSafe { /// /// 过滤字符 /// private const string StrRegex = @"^\+/v(8|9)|\b(and|or)\b.{1,6}?(=|>|<|\bin\b|\blike\b)|/\*.+?\*/|<\s*script\b|<\s*img\b|\bEXEC\b|UNION.+?SELECT|UPDATE.+?SET|INSERT\s+INTO.+?VALUES|(SELECT|DELETE).+?FROM|(CREATE|ALTER|DROP|TRUNCATE)\s+(TABLE|DATABASE)"; /// /// POST请求验证 /// /// <returns></returns> public static bool PostData() { var result = false; for (var i = 0; i < HttpContext.Current.Request.Form.Count; i++) { result = CheckData(HttpContext.Current.Request.Form[i]); if (result) { break; } } return result; } /// /// GET请求验证 /// /// <returns></returns> public static bool GetData() { var result = false; for (var i = 0; i < HttpContext.Current.Request.QueryString.Count; i++) { result = CheckData(HttpContext.Current.Request.QueryString[i]); if (result) { break; } } return result; } /// /// 请求COOKIE验证 /// /// <returns></returns> public static bool CookieData() { var result = false; for (var i = 0; i < HttpContext.Current.Request.Cookies.Count; i++) { result = CheckData(HttpContext.Current.Request.Cookies[i]?.Value.ToLower()); if (result) { break; } } return result; } /// /// 请求Referer验证 /// /// <returns></returns> public static bool Referer() { return HttpContext.Current.Request.UrlReferrer != null && CheckData(HttpContext.Current.Request.UrlReferrer.ToString()); } /// /// 字符验证 /// /// /// <returns></returns> public static bool CheckData(string inputData) { return Regex.IsMatch(inputData, StrRegex); } } }
1、web.config中配置阿里云云存储配置信息<add key="Ali_OSS_AccessKeyID" value="" /> <add key="Ali_OSS_AccessKeySecret" value="" /> <add key="Ali_OSS_BucketName" value="" /> <add key="Ali_OSS_BucketName" value="" />2、上传文件（图片）//获取上传图片 HttpPostedFileBase file = Request.Files["file0"]; if (file != null && file.ContentLength > 0) { OSS.Storage sotre = new OSS.Storage(); ImageUrl= sotre.Upload(file.FileName, file.InputStream,"Product/"); }3、阿里云云存储操作类库using Aliyun.OSS; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Als.Utils.String; namespace Als.Utils.External.Ali { public static class OssStorage { public static string AccessKeyId { get; set; } = "Ali_OSS_AccessKeyID".ValueOfAppSetting(); public static string AccessKeySecret { get; set; } = "Ali_OSS_AccessKeySecret".ValueOfAppSetting(); public static string BucketName { get; set; } = "Ali_OSS_BucketName".ValueOfAppSetting(); public static string EndPoint { get; set; } = "Ali_OSS_BucketName".ValueOfAppSetting(); #region 默认配置信息上传文件 /// /// 上传文件 /// /// 文件名 /// 文件流 public static void Upload(string fileName, Stream fileStream) { var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata { ContentType = GetContentType(fileName) }; //根据文件名设置ContentType var key = "MerLogo/" + fileName; fileStream.Seek(0, SeekOrigin.Begin); ossClient.PutObject(BucketName, key, fileStream, metadata); } /// /// 上传文件并返回结果 /// /// 文件名 /// 文件流 public static PutObjectResult UploadGetResult(string fileName, Stream fileStream) { var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata(); //根据文件名设置ContentType metadata.ContentType = GetContentType(fileName); var key = "MerLogo/" + fileName; fileStream.Seek(0, SeekOrigin.Begin); return ossClient.PutObject(BucketName, key, fileStream, metadata); } /// /// 上传文件 /// /// /// /// /// <returns>返回存储后文件路径</returns> public static string Upload(string fileName, Stream fileStream, string dir) { var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata { //根据文件名设置ContentType ContentType = GetContentType(fileName) }; var fileext = fileName.Split('.')[1]; fileName = Guid.NewGuid() + "." + fileext; var key = dir + fileName; fileStream.Seek(0, SeekOrigin.Begin); ossClient.PutObject(BucketName, key, fileStream, metadata); return dir + fileName; } #endregion #region 设置配置信息上传文件 /// /// 上传文件 /// /// /// /// /// /// 文件名 /// 文件流 public static void Upload(string accessKeyId, string accessKeySecret, string bucketName, string endPoint,string fileName, Stream fileStream) { AccessKeyId = accessKeyId; AccessKeySecret = accessKeySecret; BucketName = bucketName; EndPoint = endPoint; var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata { ContentType = GetContentType(fileName) }; //根据文件名设置ContentType var key = "MerLogo/" + fileName; fileStream.Seek(0, SeekOrigin.Begin); ossClient.PutObject(BucketName, key, fileStream, metadata); } /// /// 上传文件并返回结果 /// /// /// /// /// /// 文件名 /// 文件流 public static PutObjectResult UploadGetResult(string accessKeyId, string accessKeySecret, string bucketName, string endPoint,string fileName, Stream fileStream) { AccessKeyId = accessKeyId; AccessKeySecret = accessKeySecret; BucketName = bucketName; EndPoint = endPoint; var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata(); //根据文件名设置ContentType metadata.ContentType = GetContentType(fileName); var key = "MerLogo/" + fileName; fileStream.Seek(0, SeekOrigin.Begin); return ossClient.PutObject(BucketName, key, fileStream, metadata); } /// /// 上传文件 /// /// /// /// /// /// /// /// /// <returns>返回存储后文件路径</returns> public static string Upload(string accessKeyId, string accessKeySecret, string bucketName, string endPoint,string fileName, Stream fileStream, string dir) { AccessKeyId = accessKeyId; AccessKeySecret = accessKeySecret; BucketName = bucketName; EndPoint = endPoint; var ossClient = new OssClient(EndPoint, AccessKeyId, AccessKeySecret); var metadata = new ObjectMetadata { //根据文件名设置ContentType ContentType = GetContentType(fileName) }; var fileext = fileName.Split('.')[1]; fileName = Guid.NewGuid() + "." + fileext; var key = dir + fileName; fileStream.Seek(0, SeekOrigin.Begin); ossClient.PutObject(BucketName, key, fileStream, metadata); return dir + fileName; } #endregion #region 内部方法 /// /// 获取contentType类型 /// /// /// <returns></returns> private static string GetContentType(string fileName) { var fileNameArray = fileName.Split('.'); var contentType = string.Empty; if (fileNameArray.Length < 2) return contentType; switch (fileNameArray[1]) { case "gif": contentType = "image/gif"; break; case "png": contentType = "image/png"; break; case "jpg": contentType = "image/jpg"; break; case "rar": contentType = "application/octet-stream"; break; case "zip": contentType = "application/zip"; break; default: break; } return contentType; } #endregion } }
1、创建线程中运行的方法体public void Func(object state) { lock(obj) { ..... } }2、运行线程操作类public void FuncTask(object state) { ManagedTreadPool.QueueUserWorkItem(new WaitCallback(Func),state) }3、附线程操作类库using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; namespace Als.Utils.Task { /// ///用C#托管代码实现的线程池 /// 它在管理线程的时候，有一个缓存线程的池，即一个ArrayList对象 /// 它一开始就初始化了一定数量的线程，并通过ProcessQueuedItems方法保证异步执行进入池中的队列任务 /// 这样在分配异步任务的时候，就省去了频繁去创建（new）一个线程 /// public class ManagedThreadPool { #region Constants /// Maximum number of threads the thread pool has at its disposal. private const int _maxWorkerThreads = 10; #endregion #region Member Variables /// Queue of all the callbacks waiting to be executed. private static Queue _waitingCallbacks; /// /// Used to signal that a worker thread is needed for processing. Note that multiple /// threads may be needed simultaneously and as such we use a semaphore instead of /// an auto reset event. /// private static Semaphore _workerThreadNeeded; /// List of all worker threads at the disposal of the thread pool. private static ArrayList _workerThreads; /// Number of threads currently active. private static int _inUseThreads; /// Lockable object for the pool. private static object _poolLock = new object(); #endregion #region Construction and Finalization /// Initialize the thread pool. static ManagedThreadPool() { Initialize(); } /// Initializes the thread pool. private static void Initialize() { // Create our thread stores; we handle synchronization ourself // as we may run into situtations where multiple operations need to be atomic. // We keep track of the threads we've created just for good measure; not actually // needed for any core functionality. _waitingCallbacks = new Queue(); _workerThreads = new ArrayList(); _inUseThreads = 0; // Create our "thread needed" event _workerThreadNeeded = new Semaphore(0); // Create all of the worker threads for (int i = 0; i < _maxWorkerThreads; i++) { // Create a new thread and add it to the list of threads. Thread newThread = new Thread(new ThreadStart(ProcessQueuedItems)); _workerThreads.Add(newThread); // Configure the new thread and start it newThread.Name = "ManagedPoolThread #" + i.ToString(); newThread.IsBackground = true; newThread.Start(); } } #endregion #region Public Methods /// Queues a user work item to the thread pool. /// /// A WaitCallback representing the delegate to invoke when the thread in the /// thread pool picks up the work item. /// public static void QueueUserWorkItem(WaitCallback callback) { // Queue the delegate with no state //Logger.Debug(string.Format("添加线程操作方法:{0},Target:{1}", callback.Method.Name, callback.Target.ToString())); QueueUserWorkItem(callback, null); } /// Queues a user work item to the thread pool. /// /// A WaitCallback representing the delegate to invoke when the thread in the /// thread pool picks up the work item. /// /// /// The object that is passed to the delegate when serviced from the thread pool. /// public static void QueueUserWorkItem(WaitCallback callback, object state) { // Create a waiting callback that contains the delegate and its state. // At it to the processing queue, and signal that data is waiting. WaitingCallback waiting = new WaitingCallback(callback, state); lock (_poolLock) { _waitingCallbacks.Enqueue(waiting); } _workerThreadNeeded.AddOne(); } /// Empties the work queue of any queued work items. Resets all threads in the pool. public static void Reset() { lock (_poolLock) { // Cleanup any waiting callbacks try { // Try to dispose of all remaining state foreach (object obj in _waitingCallbacks) { WaitingCallback callback = (WaitingCallback)obj; if (callback.State is IDisposable) ((IDisposable)callback.State).Dispose(); } } catch { } // Shutdown all existing threads try { foreach (Thread thread in _workerThreads) { if (thread != null) thread.Abort("reset"); } } catch { } // Reinitialize the pool (create new threads, etc.) Initialize(); } } #endregion #region Properties /// Gets the number of threads at the disposal of the thread pool. public static int MaxThreads { get { return _maxWorkerThreads; } } /// Gets the number of currently active threads in the thread pool. public static int ActiveThreads { get { return _inUseThreads; } } /// Gets the number of callback delegates currently waiting in the thread pool. public static int WaitingCallbacks { get { lock (_poolLock) { return _waitingCallbacks.Count; } } } #endregion #region Thread Processing /// Event raised when there is an exception on a threadpool thread. #if NET1 public static event UnhandledExceptionEventHandler UnhandledException; #endif /// A thread worker function that processes items from the work queue. private static void ProcessQueuedItems() { // Process indefinitely while (true) { _workerThreadNeeded.WaitOne(); // Get the next item in the queue. If there is nothing there, go to sleep // for a while until we're woken up when a callback is waiting. WaitingCallback callback = null; // Try to get the next callback available. We need to lock on the // queue in order to make our count check and retrieval atomic. lock (_poolLock) { if (_waitingCallbacks.Count > 0) { try { callback = (WaitingCallback)_waitingCallbacks.Dequeue(); } catch { } // make sure not to fail here } } if (callback != null) { // We now have a callback. Execute it. Make sure to accurately // record how many callbacks are currently executing. try { Interlocked.Increment(ref _inUseThreads); callback.Callback(callback.State); } catch (Exception) { } finally { Interlocked.Decrement(ref _inUseThreads); } } } } #endregion /// Used to hold a callback delegate and the state for that delegate. private class WaitingCallback { #region Member Variables /// Callback delegate for the callback. private WaitCallback _callback; /// State with which to call the callback delegate. private object _state; #endregion #region Construction /// Initialize the callback holding object. /// Callback delegate for the callback. /// State with which to call the callback delegate. public WaitingCallback(WaitCallback callback, object state) { _callback = callback; _state = state; } #endregion #region Properties /// Gets the callback delegate for the callback. public WaitCallback Callback { get { return _callback; } } /// Gets the state with which to call the callback delegate. public object State { get { return _state; } } #endregion } } /// /// Implementation of Dijkstra's PV Semaphore based on the Monitor class. /// public class Semaphore { #region Member Variables /// The number of units alloted by this semaphore. private int _count; /// Lock for the semaphore. private object _semLock = new object(); #endregion #region Construction /// Initialize the semaphore as a binary semaphore. public Semaphore() : this(1) { } /// Initialize the semaphore as a counting semaphore. /// Initial number of threads that can take out units from this semaphore. /// <exception cref="ArgumentException">Throws if the count argument is less than 0.</exception> public Semaphore(int count) { if (count < 0) throw new ArgumentException("Semaphore must have a count of at least 0.", "count"); _count = count; } #endregion #region Synchronization Operations /// V the semaphore (add 1 unit to it). public void AddOne() { V(); } /// P the semaphore (take out 1 unit from it). public void WaitOne() { P(); } /// P the semaphore (take out 1 unit from it). public void P() { // Lock so we can work in peace. This works because lock is actually // built around Monitor. lock (_semLock) { // Wait until a unit becomes available. We need to wait // in a loop in case someone else wakes up before us. This could // happen if the Monitor.Pulse statements were changed to Monitor.PulseAll // statements in order to introduce some randomness into the order // in which threads are woken. while (_count <= 0) Monitor.Wait(_semLock, Timeout.Infinite); _count--; } } /// V the semaphore (add 1 unit to it). public void V() { // Lock so we can work in peace. This works because lock is actually // built around Monitor. lock (_semLock) { // Release our hold on the unit of control. Then tell everyone // waiting on this object that there is a unit available. _count++; Monitor.Pulse(_semLock); } } /// Resets the semaphore to the specified count. Should be used cautiously. public void Reset(int count) { lock (_semLock) { _count = count; } } #endregion } }
今天在整理类库，正好弄到缓存这边，就找找资料看一下。System.Web.Caching.Cache是微软提供的一个Web下的类库，Cache类，是一个用于缓存常用信息的类。HttpRuntime.Cache以及HttpContext.Current.Cache都是该类的实例。查看一个类就是从它的属性、方法等方面查看，只有了解的属性，才能明白各个方法是做什么用的。一、属性二、方法三、静态字段namespace CacheDemo { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Person p = new Person(); p.Id = 1; p.Name = "masoft"; Cache cache = HttpRuntime.Cache; cache.Insert("A",p); cache.Insert("B","字符串"); Response.Write(cache.Get("B").ToString()); //输出 字符串 Person p2 = cache["A"] as Person; Response.Write(p2.Id + " : " + p2.Name); //输出 1 : masoft Response.Write(cache.EffectivePrivateBytesLimit); //-1 只读属性 Response.Write(cache.EffectivePercentagePhysicalMemoryLimit); //98 开始移除项之前可以使用到98% Response.Write(cache.Count); //输出 3 Response.Write(cache["B"]); //输出 字符串 支持索引器式的读取 cache.Remove("BB"); //从cache中移除一项 Response.Write("~~~" + cache["B"] + "~~~"); //移除了输出 null，但程序不报错 foreach (var obj in cache) { Response.Write(obj.GetType() + " "); } } } public class Person { public int Id { get; set; } public string Name { get; set; } } }四、文件缓存依赖文件依赖已更改缓存就被清除五、绝对过期时间NoSlidingExpiration 绝对过期时间，当超过设定时间，立即移除。六、滑动过期时间NoAbsoluteExpiration 当超过设定时间没再使用时，才移除缓存七、缓存优先级[scode type="share"]//在服务器释放系统内存时，具有该优先级级别的缓存项最有可能被从缓存删除。Low = 1,//在服务器释放系统内存时，具有该优先级级别的缓存项比分配了 System.Web.Caching.CacheItemPriority.Normal//优先级的项更有可能被从缓存删除。BelowNormal = 2,//在服务器释放系统内存时，具有该优先级级别的缓存项很有可能被从缓存删除，其被删除的可能性仅次于具有 System.Web.Caching.CacheItemPriority.LowNormal = 3,//缓存项优先级的默认值为 System.Web.Caching.CacheItemPriority.Normal。Default = 3,//在服务器释放系统内存时，具有该优先级级别的缓存项被删除的可能性比分配了 System.Web.Caching.CacheItemPriority.Normal//优先级的项要小。AboveNormal = 4,//在服务器释放系统内存时，具有该优先级级别的缓存项最不可能被从缓存删除。High = 5,//在服务器释放系统内存时，具有该优先级级别的缓存项将不会被自动从缓存删除。但是，具有该优先级级别的项会根据项的绝对到期时间或可调整到期时间与其他项一起被移除NotRemovable = 6,[/scode]八、缓存移除通知应用程序Add方法的最后一个参数，委托。九、数据库依赖缓存需要配置数据库缓存模式（详情查看本文来源：http://www.cnblogs.com/kissdodog/archive/2013/05/07/3064895.html）十、组合依赖缓存当依赖的内容为多个Dependency时，可以通过AggregateCacheDependency创建依赖的组合，以便在任何一个依赖项发生变化时，使缓存项失效。组合的缓存依赖内部为一个集合，可以保存多个缓存依赖对象，将这些缓存依赖对象作为一个整体应用在缓存项目上，当其中某一个缓存依赖失效的时候，就可以使缓存的数据被丢弃。十一、System.Web.Caching.Cache Insert和Add方法的区别[scode type="share"]比较、区别 a). Insert方法支持5种重载，使用灵活，而Add方法必须提供7个参数； b). Add方法可以返回缓存项的数据对象，Insert 返回Void； c). 添加重复缓存情况下(Key已存在)，Insert会替换该项，而Add方法则不执行任何操作，并返回原来保存的object对象(Update 2014-03-18)。 过期策略 a). 永不过期 Insert(string key, object value); b). 绝对时间过期 DateTime.Now.AddSeconds(10)表示缓存在10秒后过期，TimeSpan.Zero表示不使用平滑过期策略。 例：Cache.Insert("Data", ds,null, DateTime.Now.AddSeconds(10), TimeSpan.Zero); c). 变化时间过期（平滑过期） DateTime.MaxValue表示不使用绝对时间过期策略，TimeSpan.FromSeconds(10)表示缓存连续10秒没有访问就过期。 例：Cache.Insert("Data", ds, null, DateTime.MaxValue, TimeSpan.FromSeconds(10));[/scode]十二、清除缓存清空缓存主要通过Remove()方法，但是只能通过传入一个Key，清空一个。GetEnumerator()方法用于获取所有缓存项。MoveNext()用于将位置移动到下一个缓存项。如果想清空所有缓存，由于Cache类没有提供RemoveAll()方法我们只能Count循环删除
今天逛CNBLOGS，看到一篇关于ASP.NET中Web.config配置文件的基本使用方法。我感觉挺有用处的，我就转载一下。以后有需要可以查阅一下。该文章是作者花了点时间整理的。很适合新手参看，由于Web.config在使用很灵活，可以自定义一些节点。所以这里只介绍一些比较常用的节点。<?xml version="1.0"?> <!--注意: 除了手动编辑此文件以外，您还可以使用 Web 管理工具来配置应用程序的设置。可以使用 Visual Studio 中的“网站”->“Asp.Net 配置”选项。 设置和注释的完整列表在 machine.config.comments 中，该文件通常位于 "Windows"Microsoft.Net"Framework"v2.x"Config 中。--> <configuration> <configSections> <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"> </sectionGroup> </sectionGroup> </configSections> <appSettings> <add key="1" value="1" /> <add key="gao" value="weipeng" /> </appSettings> <connectionStrings> <add name="ConnString" connectionString="Data Source=GAO;Initial Catalog=HBWXDate;User ID=sa;password=sa"></add> <add name="111" connectionString="11111" /> </connectionStrings> <location path="Default.aspx" allowOverride="false"> <system.web> <identity impersonate="false" /> <!--标识特定于页的配置设置（如是否启用会话状态、视图状态，是否检测用户的输入等）。<pages>可以在计算机、站点、应用程序和子目录级别声明. 这里的几个属性的意思是默认主页为Index,主题是Default，不检测用户在浏览器输入的内容中是否存在潜在的危险数据（注：该项默认是检测，如果你使用了不检测，一要对用户的输入进行编码或验证)，在从客户端回发页时将检查加密的视图状态，以验证视图状态是否已在客户端被篡改。(注：该项默认是不验证）禁用ViewState--> <pages masterPageFile="Index" theme="Default" buffer="true" enableViewStateMac="true" validateRequest="false" enableViewState="false"> <controls></controls> <namespaces></namespaces> </pages> <customErrors defaultRedirect="Err.html" mode="RemoteOnly"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> <trace enabled="true" localOnly="false" pageOutput="true" requestLimit="15" traceMode="SortByCategory"/> <compilation debug="true" defaultLanguage="c#" batch="false"> <assemblies> <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add assembly="System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> <add assembly="System.Web.Services, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> </assemblies> <buildProviders> <add extension=".aspx" type="System.Web.Compilation.PageBuildProvider"/> <add extension=".ascx" type="System.Web.Compilation.UserControlBuildProvider"/> <add extension=".master" type="System.Web.Compilation.MasterPageBuildProvider"/> <add extension=".asmx" type="System.Web.Compilation.WebServiceBuildProvider"/> <add extension=".ashx" type="System.Web.Compilation.WebHandlerBuildProvider"/> <add extension=".soap" type="System.Web.Compilation.WebServiceBuildProvider"/> <add extension=".resx" type="System.Web.Compilation.ResXBuildProvider"/> <add extension=".resources" type="System.Web.Compilation.ResourcesBuildProvider"/> <add extension=".wsdl" type="System.Web.Compilation.WsdlBuildProvider"/> <add extension=".xsd" type="System.Web.Compilation.XsdBuildProvider"/> <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.Common, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/> </buildProviders> </compilation> <!--通过 <authentication> 节可以配置 ASP.NET 使用的 安全身份验证模式，以标识传入的用户。Windows: 使用IIS验证方式,Forms: 使用基于窗体的验证方式,Passport: 采用Passport cookie验证模式,None: 不采用任何验证方式--> <authentication mode="Forms"> <forms name=".ASPXUSERDEMO" loginUrl="Login.aspx" protection="All" timeout="30"/> </authentication> <!--控制对 URL 资源的客户端访问（如允许匿名用户访问）。此元素可以在任何级别（计算机、站点、应用程序、子目录或页）上声明。必需与<authentication> 节配合使用。此处的意思是对匿名用户不进行身份验证。拒绝用户weipeng--> <authorization> <allow users="*"/> <deny users="weipeng"/> <allow users="aa" roles="aa" /> </authorization> <globalization requestEncoding="gb2312" responseEncoding="gb2312" fileEncoding="gb2312" /> <sessionState mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20"></sessionState> <sessionPageState historySize="9"/> <httpRuntime appRequestQueueLimit="100" executionTimeout="80" maxRequestLength="40960" useFullyQualifiedRedirectUrl="false"/> <httpModules> <add name="OutputCache" type="System.Web.Caching.OutputCacheModule" /> <add name="Session" type="System.Web.SessionState.SessionStateModule" /> <add name="WindowsAuthentication" type="System.Web.Security.WindowsAuthenticationModule" /> <add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" /> <add name="PassportAuthentication" type="System.Web.Security.PassportAuthenticationModule" /> <add name="RoleManager" type="System.Web.Security.RoleManagerModule" /> <add name="UrlAuthorization" type="System.Web.Security.UrlAuthorizationModule" /> <add name="FileAuthorization" type="System.Web.Security.FileAuthorizationModule" /> <add name="AnonymousIdentification" type="System.Web.Security.AnonymousIdentificationModule" /> <add name="UrlRewriter" type="Intelligencia.UrlRewriter.RewriterHttpModule, Intelligencia.UrlRewriter" /> <add name="Profile" type="System.Web.Profile.ProfileModule" /> </httpModules> <httpHandlers> <remove verb="*" path="*.asmx"/> <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory, AjaxPro.2"/> </httpHandlers> <httpCookies httpOnlyCookies="false" requireSSL="false"/> <webServices> <protocols> <add/> </protocols> </webServices> <caching> <cache disableMemoryCollection = "false" disableExpiration = "false" privateBytesLimit = "0" percentagePhysicalMemoryUsedLimit = "90" privateBytesPollTime = "00:02:00"/> <!--设计需要以这种方式缓存的页时，您需要向该页添加以下指令：<%@ OutputCache CacheProfile="ServerOnly" %>--> <outputCacheSettings> <outputCacheProfiles> <add name="ServerOnly" duration="60" varyByCustom="browser" location="Server" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web> </location> <system.net> <mailSettings> <smtp from="weipeng"> <network host="Gao" password="" userName="" /> </smtp> </mailSettings> <requestCaching disableAllCaching="true"></requestCaching> <defaultProxy> <proxy usesystemdefault="True" proxyaddress="http://192.168.1.10:3128" bypassonlocal="True"/> <bypasslist> <add address="[a-z]+".contoso".com" /> </bypasslist> </defaultProxy> </system.net> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <modules> <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </modules> <handlers> <remove name="WebServiceHandlerFactory-Integrated"/> <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </handlers> </system.webServer> <system.web.extensions> <scripting> <webServices> <jsonSerialization maxJsonLength="5000"/> </webServices> </scripting> </system.web.extensions> <system.serviceModel> <services> <service name="WCFStudent.WCFStudentText" behaviorConfiguration="ServiceBehavior"> <endpoint address="" binding="wsHttpBinding" contract="WCFStudent.IStuServiceContract"> <identity> <dns value="localhost"/> </identity> </endpoint> <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/> </service> </services> <behaviors> <serviceBehaviors> <behavior name="ServiceBehavior"> <serviceMetadata httpGetEnabled="true"/> <serviceDebug includeExceptionDetailInFaults="false"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel> <rewriter> <rewrite url="~/user/u(.+).aspx" to="~/user/index.aspx?r=$1" /> <rewrite url="~/ask/q(.+).aspx" to="~/home/ask/content.aspx?id=$1" /> <rewrite url="~/blog/b(.+).aspx" to="~/home/blog/article.aspx?r=$1" /> <rewrite url="~/news/n(.+).aspx" to="~/home/news/content.aspx?nid=$1" /> <rewrite url="~/default.aspx" to="~/home/ram/net.aspx" /> </rewriter> </configuration>