代码:通过避免下列 10 个常见 ASP.NET 缺陷使网站平稳运行(转)

代码转自微软中文MSDN:http://msdn.microsoft.com/msdnmag/issues/06/07/WebAppFollies/default.aspx?fig=true#fig1
Figure 1 MyUserControl

MyUserControl.ascx
<%@ Control Language="C#" AutoEventWireup="true"
CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl"
%>
<h1><asp:Label ID="Label1" runat="server" Text="Label" /></h1>

MyUserControl.ascx.cs
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
public partial class MyUserControl : System.Web.UI.UserControl
{
public Color BackColor
{
get { return Label1.BackColor; }
set { Label1.BackColor = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongTimeString();
}
}

Figure 2 The Proper Way to Load MyUserControl.ascx
protected void Page_Load(object sender, EventArgs e)
{
// Load the user control
Control control = LoadControl("~/MyUserControl.ascx");
PlaceHolder1.Controls.Add(control);
// Set its background color (if possible)
MyUserControl uc = control as MyUserControl;
if (uc == null)
{
PartialCachingControl pcc = control as PartialCachingControl;
if (pcc != null) uc = pcc.CachedControl as MyUserControl;
}
if (uc != null) uc.BackColor = Color.Yellow;
}

Figure 3 Limiting Persistent Authentication Cookie Lifetime
void Application_EndRequest(Object sender, EventArgs e)
{
// Change the expiration date on outgoing persistent forms
// authentication tickets to 24 hours hence.
HttpCookie cookie1 = GetCookieFromResponse(
FormsAuthentication.FormsCookieName);
if (cookie1 != null && !String.IsNullOrEmpty (cookie1.Value))
{
FormsAuthenticationTicket ticket1 = FormsAuthentication.Decrypt(
Response.Cookies[FormsAuthentication.FormsCookieName].Value);
if (ticket1.IsPersistent)
{
FormsAuthenticationTicket ticket2 =
new FormsAuthenticationTicket (
ticket1.Version, ticket1.Name, ticket1.IssueDate,
DateTime.Now.AddHours (24), // New expiration date
ticket1.IsPersistent, ticket1.UserData,
ticket1.CookiePath
);
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
HttpCookie cookie2 = new HttpCookie(
FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket2));
cookie2.Expires = ticket2.Expiration;
Response.Cookies.Add(cookie2);
}
}
}
HttpCookie GetCookieFromResponse (string name)
{
HttpCookieCollection cookies =
HttpContext.Current.Response.Cookies;
int count = cookies.Count;
for (int i=0; i<count; i++) {
if (String.Compare (cookies[i].Name, name, true) == 0)
return cookies[i];
}
return null;
}

Figure 4 Storing View State in Session State in ASP.NET 1.x
protected override object LoadPageStateFromPersistenceMedium ()
{
string key = Request.RawUrl + &quot;_VIEWSTATE&quot;;
object state = Session[key];
return (state == null) ?
base.LoadPageStateFromPersistenceMedium () : state;
}
protected override void
SavePageStateToPersistenceMedium (object viewState)
{
string key = Request.RawUrl + &quot;_VIEWSTATE&quot;;
Session[key] = viewState;
}

Figure 6 Custom Data Type Used Incorrectly

Class Definition
public class Posts
{
private int _count = 0;
public void IncrementPostCount()
{
_count++;
}
public int GetPostCount()
{
return _count;
}
}

Profile Definition
<profile>
<properties>
<add name="Posts" type="Posts" />
</properties>
</profile>

Figure 7 Custom Data Type Used Properly

Class Definition
[Serializable]
public class Posts
{
private int _count = 0;
public void IncrementPostCount()
{
_count++;
}
public int GetPostCount()
{
return _count;
}
}

Profile Definition
<profile>
<properties>
<add name="Posts" type="Posts" serializeAs="Binary" />
</properties>
</profile>

Figure 8 ASP.NET Pitfalls Checklist

Does your app use LoadControl to load user controls dynamically? If so, make sure this is done in such a way that LoadControl will work both with and without output caching.
Are you using kernel-mode output caching and session state in the same page? If so, remove the OutputCache directive to avoid caching that page or turn kernel-mode output caching off for the entire app.
Are you calling FormsAuthentication.RedirectFromLoginPage in your ASP.NET 1.x-based app? If so, either change the second parameter to false or modify the Expires property of outgoing persistent forms authentication cookies to a more appropriate timeout.
Do any of your pages generate inordinate amounts of view state? If so, turn off view state for individual controls or keep it on the server.
Does your app use SQL Server session state? If so, make sure you disable sessions in pages that don’t use sessions.
Does your app use the ASP.NET 2.0 role manager? If so, enable role caching to increase performance.
Does your app use custom data types as profile properties? If so, you'll avoid problems by creating custom data types that are compatible with XML serialization or by attributing the types as serializable and using the binary serializer to serialize and deserialize types.
Does your app do database queries that take a long time to return? If so, consider whether the pages are candidates for becoming asynchronous.
Does your ASP.NET app use client impersonation? If so, simple authentication in ASP.NET might enforce ACL-based permissions with less hassle.
Have you profiled your app’s database activity? Examining communication between the app and database is a good first performance-tuning step.
posted @ 2006-07-18 21:46  David  Views(277)  Comments(0)    收藏  举报
Freelance Jobs