代码改变世界

ASP.NET 小记

2010-07-26 21:11  音乐让我说  阅读(412)  评论(0编辑  收藏  举报
  1. 微软ASP.NET 验证控件验证通过后:
    <script type="text/javascript">
            function OnValidateSuccess()
            {
                if(Page_ClientValidate())
                {
                    //验证通过,如果有多个验证组,则需要用:if(Page_ClientValidate("vgMainInfo")) {  }
                }
            }
    </script>
    
    <form id="form1" runat="server">
        <div>
            姓名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="rfv" runat="server" Text="*" ControlToValidate="txtName"></asp:RequiredFieldValidator>
            <br />
            年龄:<asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
            <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" Text="*"
                ControlToValidate="txtAge"></asp:RequiredFieldValidator>
            <asp:CompareValidator ID="CompareValidator1" runat="server" Text="请输入正整数" ControlToValidate="txtAge"
                Operator="GreaterThan" Type="Integer" ValueToCompare="0"></asp:CompareValidator>
            <br />
            <asp:Button ID="btnSubmit" runat="server" Text=" 提 交 " OnClientClick="return OnValidateSuccess();"/>
        </div>
    </form>

     

  2. 加密web.config文件:
    aspnet_regiis.exe -pef "connectionStrings" "D:\VS Workspace\WebUI" -prov "DataProtectionConfigurationProvider"
  3. 解密web.config文件:
    aspnet_regiis.exe -pdf "connectionStrings" "D:\VS Workspace\WebUI"

     

  4. 不需要附加数据库,就可以运行asp.net程序的连接字符串,不推荐:
    <add name="connString" connectionString="Data Source=.\SQLExpress;AttachDbFilename=|DataDirectory|Test_data.mdf;Integrated Security=True;User Instance=True" />

     

  5. 高亮显示关键字:
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>无标题页</title>
        <script language="javascript" type="text/javascript">
            function InitData()
            {
                document.body.innerHTML = document.body.innerHTML.replace(/(甲流)/g,"<span style='color:red;font-weight:bold;'>$1</span>");
            }
        </script>
    </head>
    <body onload="InitData();">
        <div>
            数量多看加拉塞克的甲流脸色看大家力困衰怠竭了四度空间<br />
            数量多看剑履上殿开房间甲流是独立开发就死定了技术的离开<br />
            就是懒得看接待费<br />
            甲流<br />
            思路打开附件实甲流力都开放<br />
        </div>
        
    </body>
    </html>

     

  6. C#中的string类的Trim方法可以重载:
    如:string a = "===你好===";
    string b = a.Trim('=');
    
    将得到“你好”;
    
  7. 让一个服务器端按钮成为普通按钮:
    <cc1:PerfectButton ID="btnViewDetails" Text="查 看" CssClass="sbutton" runat="server"
    AuthorityId="432" OnClientClick='<%# Eval("UserId","return ViewDetails({0})")%>' UseSubmitBehavior="false" />

     

  8. 解决IFrame Cookie 问题:
    Response.AddHeader("P3P", "CP=CAO PSA OUR");

     

  9. 网站注册时,要严格限制登录名,不能出现引号(" ")、杠号("\")等等。
  10. 客户端和服务器端都不缓存:
    <%@ OutputCache Location="None" %>

     

  11. 返回当前应用程序的根目录:
    AppDomain.CurrentDomain.BaseDirectory

     

  12. 获得一个匿名对象的属性:
    TypeDescriptor.GetProperties  或 DataBinder.Eval(item, "ProductName")

     

  13. App_Browsers文件夹:\App_Browsers文件夹包含.browser文件,这些.browser文件是XML文件,用于标识向应用程序发出请求的浏览器,并识别这些浏览器具备的功能。C:\Windows\Microsoft.NET\ Framework\v2.0.50727\CONFIG\Browsers上有可全局访问的.browser文件列表。另外,如果要修改这些默认浏览器定义文件中的任意部分,只需把相应的.browser文件从Browsers文件夹复制到应用程序的\App_Browsers文件夹中,并修改定义即可。
  14. 记住:
    TCP、IP、HTTP、SMTP、WWW、FTP、HTML、URL的含义。
       (1)TCP(Transmission Control Protocol)传输控制协议
       (2)IP(Internet Protocol)网络之间互联的协议/网络协议
       (3)HTTP(HyperText Transfer Protocol)超文本传输协议
       (4)SMTP(Simple Mail Transfer Protocol)简单电子邮件协议
       (5)WWW(World Wide Web)万维网
       (6)FTP(File Transfer Protocol)文件传输协议
       (7)HTML(Hypertext Markup Language)超文本标记语言
       (8)URL(Uniform Resource Locator)统一资源定位符
    
  15. URL 的一个例子:
    http://www.mywebsite.com/sj/test/test.aspx?name=sviergn&x=true#stuff
    
    Schema:                 http
    host:                   www.mywebsite.com
    path:                   /sj/test/test.aspx
    Query String:           name=sviergn&x=true
    Anchor:                 stuff

     

  16. 获得请求的扩展名:
    string filePath = Request.RawUrl;
                    string fileExtension = VirtualPathUtility.GetExtension(filePath);
    
                    this.ltMessage.Text = "后缀名为:" + fileExtension + "!";
    
  17. 在10秒里如果没有点击“btnSubmit”按钮(即没有读取Cache["Time"]),则缓存过期:
     /// <summary>
            /// 加载事件
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            protected void Page_Load(object sender, EventArgs e)
            {
                if(!IsPostBack)
                {
                    Cache.Remove("Time");
                }
                string strDateTime = DateTime.Now.ToString();
                ltCurrentMessage.Text = strDateTime;
    
                if (Cache["Time"] == null)
                {
                    // Save cache with key "Time" using Cache's Insert method and set its sliding time to 10s 
                    Cache.Insert("Time", strDateTime, null, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromSeconds(10));
                }
                ltMessage.Text = Cache["Time"].ToString();
            }
    
            protected void btnSubmit_Click(object sender, EventArgs e)
            {
    
            }
    
  18. <%: %> 实际上调用的是 System.Web.HttpUtility 的 HtmlEncode 方法,该方法有 3 个重载,其中有一个 Object 的参数的重载,该方法内部 IHtmlString a = value as

    IHtmlString,由于 MvcString 也实现了这个借口,所有 <%: Html.ActionLink("关于","about","Home") %> 返回的 Html 是 <a href="/Home/about">关于</a>

  19. 自定义验证文本域的字符长度
        <script type="text/javascript">
    function CustomValidateCommon(htmlSpanObj, args, maxWordLength)
    {
    if (args.Value.length > maxWordLength)
    {
    args.IsValid
    = false;
    }
    }
    function CustomValidateDescription(sender, args)
    {
    CustomValidateCommon(sender, args,
    80);
    }
    </script>



    描述:<asp:TextBox ID="txtDescription" runat="server" Width="300px" Height="100px" TextMode="MultiLine"></asp:TextBox>
    <asp:CustomValidator ID="rvDescription" runat="server" ControlToValidate="txtDescription"
    ClientValidationFunction
    ="CustomValidateDescription"
    SetFocusOnError
    ="true" Text="字数过多" Display="Dynamic">
    </asp:CustomValidator>
    提示:不超过80字
  20. HttpRuntime 下常用的属性:
    HttpRuntime.BinDirectory :获取当前应用程序的 /bin 目录的物理路径。
    
    示例:D:\VS Workspace\DearBruce.EfMvcDemo\DearBruce.EfMvcDemo.MvcUI\bin\
    
    
    HttpRuntime.CodegenDir: 获取 ASP.NET 存储当前应用程序的临时文件(生成的源、编译了的程序集等)的目录的物理路径。
    
    示例:C:\Users\res-zlliu\AppData\Local\Temp\Temporary ASP.NET Files\root\27cee896\412495e5 
    
    
    HttpRuntime.MachineConfigurationDirectory:获取当前应用程序的 Machine.config 文件所在目录的物理路径。
    
    示例:C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config

     

  21. HttpHandler 响应图片请求:
    if (reader.Read())
    {
        byte[] imgbytes = null;
        string imgtype = null;
    
        if (reader.GetValue(0) != DBNull.Value)
        {
            imgbytes = (byte[])reader.GetValue(0);
            imgtype = reader.GetString(1);
    
            // If bmp, convert to jpg and show because of the different formation type.
            if (imgtype.Equals("image/bmp", StringComparison.OrdinalIgnoreCase))
            {
                using (MemoryStream ms = new MemoryStream(imgbytes))
                {
                    using (Bitmap bm = new Bitmap(Image.FromStream(ms)))
                    {
                        bm.Save(context.Response.OutputStream, ImageFormat.Jpeg);
                    }
                }
            }
            else
            {
                context.Response.ContentType = imgtype;
                context.Response.BinaryWrite(imgbytes);
            }
        }
        else
        {
            imgbytes = File.ReadAllBytes(context.Server.MapPath
                ("~/DefaultImage/DefaultImage.JPG"));
            imgtype = "image/pjpeg";
            context.Response.ContentType = imgtype;
            context.Response.BinaryWrite(imgbytes);
        }
    }

     

  22. ASP.NET 中利用 System.Web.Security.MachineKey 来加密、解密数据。
            string Protect(byte[] data)
            {
                if (data == null || data.Length == 0) return null;
    
                return MachineKey.Encode(data, MachineKeyProtection.All);
            }
    
            byte[] Unprotect(string value)
            {
                if (String.IsNullOrWhiteSpace(value)) return null;
    
                return MachineKey.Decode(value, MachineKeyProtection.All);
            }
    
            byte[] Compress(string value)
            {
                if (value == null) return null;
    
                var data = Encoding.UTF8.GetBytes(value);
                using (var input = new MemoryStream(data))
                {
                    using (var output = new MemoryStream())
                    {
                        using (Stream cs = new DeflateStream(output, CompressionMode.Compress))
                        {
                            input.CopyTo(cs);
                        }
    
                        return output.ToArray();
                    }
                }
            }
    
            string Decompress(byte[] data)
            {
                if (data == null || data.Length == 0) return null;
    
                using (var input = new MemoryStream(data))
                {
                    using (var output = new MemoryStream())
                    {
                        using (Stream cs = new DeflateStream(input, CompressionMode.Decompress))
                        {
                            cs.CopyTo(output);
                        }
    
                        var result = output.ToArray();
                        return Encoding.UTF8.GetString(result);
                    }
                }
            }

     

  23. 把 ASP.NET 2.0 的项目部署在基于 ASP.NET 4.0.30319 的 IIS 上,如果网站需要提交包含 Html 的表单内容,那么需要在 Web.Config 中配置:
    <httpRuntime requestValidationMode="2.0"/>

     

  24. 代替 Server.MapPath 的方法:
    System.Web.Hosting.HostingEnvironment.MapPath("/");

     

  25. 关于 System.Web.VirtualPathUtility 类的 IsAppRelative 使用用法。
    bool flag1 = System.Web.VirtualPathUtility.IsAppRelative("~/hello.aspx"); // true
    bool flag2 = System.Web.VirtualPathUtility.IsAppRelative("/hello.aspx"); // false
    bool flag3 = System.Web.VirtualPathUtility.IsAppRelative("hello.aspx"); // false
    bool flag4 = System.Web.VirtualPathUtility.IsAppRelative("http://www.baidu.com/hello.aspx"); // false

     其它:

    string appVirtualPath = HttpRuntime.AppDomainAppVirtualPath;
    Response.Write(appVirtualPath + "<br/>"); // 结果: /
    
    string basePath = VirtualPathUtility.AppendTrailingSlash(appVirtualPath);
    Response.Write(basePath + "<br/>"); // 结果: /
    
    string fullyQualifiedPath1 = VirtualPathUtility.Combine(basePath, "hello.aspx");
    Response.Write(fullyQualifiedPath1 + "<br/>"); // 结果: /hello.aspx
    
    string fullyQualifiedPath2 = VirtualPathUtility.Combine(basePath, "/hello.aspx");
    Response.Write(fullyQualifiedPath2 + "<br/>"); // 结果:/hello.aspx
    
    string fullyQualifiedPath3 = VirtualPathUtility.Combine(basePath, "~/hello.aspx");
    Response.Write(fullyQualifiedPath3 + "<br/>"); // 结果:~/hello.aspx

     

  26. ASP.NET 临时文件夹的路径
    ASP.NET 临时文件夹的路径:    C:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\vs
    
    IIS 临时文件夹的路径    :    C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root

     

  27. 谢谢浏览...