Building ASP.NET application - Best Practices
We are building an ASP.NET application and would like to follow the best practices. Some of the best practices are:
Server side Code:
- Use catch blocks to trap & log low level errors too.
- Use Cache objects to populate dropdowns etc. where we won’t expect the changes in the underlying data/database.
- In case of error logging framework, provide emailing alerts along开发者_Python百科 with logging the errors.
HTML code: - Don’t write inline CSS. - Place the JavaScript code (If needed by the page) at the end of the page unless the page needs it for load time actions.
Now coming to the point, Would you please share these best practice points if you have a comprehensive list of them already?
Some of the best practices that I've learned over time and written up for use at my company...many are mainly applicable to WebForms and not MVC.
- Don't write .NET code directly in your ASPX markup (unless it is for databinding, i.e. Evals). If you have a code behind, this puts code for a page in more than one place and makes the code less manageable. Put all .NET code in your code-behind.
- SessionPageStatePersister can be used in conjunction with ViewState to make ViewState useful without increasing page sizes. Overriding the Page's PageStatePersister with a new SessionPageStatePersister will store all ViewState data in memory, and will only store an encrypted key on the client side.
- Create a BasePage that your pages can inherit from in order to reuse common code between pages. Create a MasterPage for your pages for visual inheritance. Pages with vastly different visual styles should use a different MasterPage.
- Create an enum of page parameter key names on each WebForm that are passed in via the URL, to setup strongly-typed page parameters. This prevents the need for hard-coded page parameter key strings and their probable mis-typing, as well as allowing strongly-typed parameter access from other pages.
- Make use of the ASP.NET Cache in order to cache frequently used information from your database. Build (or reuse from another project) a generic caching layer that will wrap the ASP.NET Cache.
- Wrap ViewState objects with Properties on your Pages to avoid development mistakes in spelling, etc. when referencing items from the ViewState collection.
- Avoid putting large objects and object graphs in ViewState, use it mainly for storing IDs or very simple DTO objects.
- Wrap the ASP.NET Session with a SessionManager to avoid development mistakes in spelling, etc. when referencing items from Session.
- Make extensive use of the applicationSettings key/value configuration values in the web.config - wrap the Configuration.ApplicationSettings with a class that can be used to easily retrieve configuration settings without having to remember the keys from the web.config.
- Avoid the easiness of setting display properties on your UI controls, instead use CSS styles and classes - this will make your styles more manageable.
- Create UserControls in your application in order to reuse common UI functionality throughout your pages. For example, if a drop down list containing a collection of categories will be used in many places in the site - create a CategoryPicker control that will data bind itself when the page is loaded.
- Use Properties on your UserControls to setup things like default values, different displays between pages, etc. Value type properties can be defined on your UserControls and then be set in your ASP.NET markup by using class level properties on UserControls.
- Make use of the ASP.NET validation controls to perform simple validations, or use the CustomValidator to perform complex validations.
- Create an Error handling page that can be redirected to when an unhandled exception occurs within your website. The redirection can occur via the Page_Error event in your Page, the Application_Error event in your Global.asax, or within the section within the web.config.
- When working with pages that use a highly dynamic data driven display, use the 3rd party (free) DynamicControlsPlaceholder control to simplify the code needed to save the state of dynamically added controls between postbacks.
Create a base page for all your asp.net pages. This page will derive from System.Web.UI.Page and you may put this in YourApp.Web.UI. Let all your asp.net pages dervice from YourApp.Web.UI.Page class. This can reduce lot of pain.
Use Application_OnError handler to gracefully handle any error or exception. You should log the critical exception and send the details of the exception along with date-time and IP of client to the admin email id. Yes ELMAH is sure way to go.
Use ASP.NET Themes. Many developers don't use it. Do use them - they are a great deal.
Use MembershipProvider and RoleProvider. And Never use inbuilt ProfileProvider - They store everything in plain strings. It will drastically slow-down the performance while performing R/W
Use Firebug for client-side debugging. Try to follow YSlow standards for web-applications. Use YSlow extension for FireBug.
Use jQuery for client-scripting.
Never store User Authentication information in session or don't use sessions to judge if user is logged on. Store only minimum necessary information in sessions.
Have a look at PostSharp. Can improve maintainability of your code and make you more productive.
Never ever Deploy asp.net application under debug configuration on production. Find out here what scottgu has to say about this.
User Web Deployment projects. It can transform web.config sections and replace with production server setings. It will merge all compiled code-behind classes into one single assembly which is a great deal.
Use Cookie-less domains to serve static resources like images, scripts, styles etc. Each client request is sent along with whole bunch of cookies, you don't need cookies while serving pictures or scripts. So host those resources on a cookie-less domain.
Minify scripts, stylesheets and HTML response from the server. Removing unnecessary line-breaks and white-spaces can improve the time-to-load and bandwidth optimization.
Forms:
Set
Page.Form.DefaultFocus
andPage.Form.DefaultButton
to improve user experienceCheck
Page.IsValid
in your Save button handler before proceeding.
General:
Understand and implement the techniques found in the article "TRULY Understanding ViewState"
Use Page.IsPostBack in your page events to stop code from running unnecessarily.
Use hyperlinks instead of posting and using Response.Redirect whenever possible.
a. Understand and use the second parameter of Response.Redirect (it "Indicates whether execution of the current page should terminate")
Use the Page Lifecycle properly.
Use the Per-Request cache (HttpContext.Items) instead of Cache where it makes sense.
Web.Config:
Deploy with
<compilation debug="false">
Register your controls at the web.config level instead of the page level (i.e. @Register).
Themes:
When using Themes, put your static images in the Theme as well.
a. Don't link to the images directly from your markup, link to them from a skin file or css file in your Theme instead.
ex:
<asp:Image SkinID="MyImage" runat="server" ImageUrl="Images/myImage.gif" />
I don't think try/catch blocks are always appropriate for low-level methods. You want to catch (and log/alert, even better!) any errors before they get to the user, of course. But it is often better for a low-level method to just lets its errors get raised up to a higher level. The problem I have seen with low-level error trapping is that it often lets a larger operation continue, but then a result that is not quite correct gets presented to the user or saved to the database, and in the long run it's much more difficult to fix. It's also just a lot of extra clutter in your code to put a try/catch at every level if you're not going to "do anything" with the error until it's raised up to a higher level.
Here are some similar questions that may help you.
.NET best practices?
Best way to learn .NET/OOP best practices?
This should probably be community wiki as well.
I would recommend a couple of books if you are interested in pursuing a journey to become a better, more productive developer. These books are language agnostic and as you can see by the user reviews, very very helpful.
Code Complete 2
Pragmatic Programmer
If you are looking for a .NET specific book, you may appreciate the following book:
Microsoft Application Architecture Guide [available online for free outside of print format]
ASP.NET
- If you don't use Session state, don't forget to turn off it.
- Use
Server.Transfer
instead ofResponse.Redirect
if possible. - Set expiration parameter in IIS.
- Use GZip to compress the text files.
- Use Server-Side and Client-Side validation together.
- Use Url Rewriter or Routing to make friendly url for SEO.
Design
- Write each class and its properties of your CSS file in the same line. (To decrease the file size)
- Use CSS Sprites. (To decrease request)
精彩评论