Hello World:解剖 ASP.NET 项目

Hello World: An Anatomy of an ASP .NET Project

by Kaushal Sanghavi


Ever since Kernighan and Ritchie wrote a program to display "Hello World" in the C language, programming has never been the same. I have learnt and programmed a variety of new languages since then, and my first attempt at each new programming language has been to greet the world with a "Hello World". ASP .NET is not just a new revision of ASP. It is not ASP 4.0. It is a completely new paradigm and a new programming model and language. What better way to be introduced to this language than with a Hello World?

In this article, I will attempt to write a simple "Hello World" and explain all the code that goes behind this. ASP .NET generates a lot of code and files for you to support the notion of a Web Application, and we will dig into the details of an ASP .NET project.

A note about the attached code is due here. Due to the multiple files that VS .NET creates, the references to drives, and folders, it turned out to be very difficult for me to zip up all the code and link it to this document. It would have been next to impossible for someone to download this code and get it working "out of the box". As a result, I am only attaching the HelloWorld.aspx and HelloWorld.vb files and I would recommend you create an empty ASP .NET project and add these files to your project. A zipped version of the source code is available for download from here.

How to Create an ASP .NET Project

Creating an ASP .NET project is fairly simple. You will need to have the Beta 1 version of Microsoft Visual Studio .NET. In reality, you don't need this tool, it is possible to open up your favorite editor and start typing, but VS .NET provides a whole lot more than your simple Notepad. I will focus on creating ASP .NET projects using Microsoft VS .NET Beta 1. In order to create an ASP .NET project, follow these simple steps.

  1. Chose "New Project" from VS .NET IDE.
  2. Under the "Project Type", select "Visual Basic Projects" and chose the "Web Application Template".
  3. Enter the name of your ASP .NET project (ASPHelloWorld in this case) and voila! You have just created your first ASP .NET project.
  4. Rename the WebForm1.aspx to a more meaningful name. In this sample, I have renamed it to HelloWorld.aspx and this is how I will refer to it in this article.

Files generated by VS .NET

When you create an ASP .NET project, VS .NET by default creates the following main files for you. You should be able to view and open these files using the Solution Explorer. Let me start with a list of these files and a quick description of this. In the next section, I will deep deeper into each file and try to explain each in more detail.

Used for dynamic discovery of Web Services
Contains the configuration settings for this Web Application
Similar to the Global.asa file. Contains global events for this Web Application
This contains the event handling code corresponding to the Global.asax
HelloWorld.aspx (by default, this file is called WebForm1.aspx)
Blank by default. This is where your ASP/HTML controls go in.
This contains the event handling code for the corresponding .aspx file
Style sheet that can be used across the application

In addition to these, VS .NET also creates the following files that are used internally by VS .NET. These contain details about the project settings etc. I would recommend you to open these in notepad and view them in order to understand how VS .NET uses these, but be careful not to modify these. Modifying these files could cause VS .NET to not recognize your project and not be able to open the solution.

ASPHelloWorld.sln ASPHelloWorld.suo ASPHelloWorld.vbproj ASPHelloWorld.vbproj.webinfo

Digging into Code

Now that we have covered the basics, its time to dig into the real code.

Please enter your name

This is what the HelloWorld webform looks like. It asks you for your name and then proceeds to greet the world "Hello World" followed by your name in parenthesis.

Hello World (by Kaushal)

Now that we know what the code does, lets dive into the code.

HelloWorld.aspx Details

Lets start with digging into the details of the .aspx file that has been generated. Keep in mind, I have not written a single line of HTML for this. This is a very VB-sque experience. VS .NET provides a standard Toolbox that contains WebForm controls, HTML controls, Server controls etc, and building the UI is as simple as dragging and dropping these controls and setting their properties in the Properties window (again a feature inspired by the VB 6.0 Properties window). I will take certain sections of the generated code and discuss this. If you want to see how these sections fit together, or would like to look at the code in its entirety, I would suggest that you open the code (from the zip file) in VS .NET and follow along.

Page Level Attributes

The first thing you will notice when you open up the HelloWorld.aspx in an editor is this line:

<%@ Page Language="vb" Codebehind="HelloWorld.vb" Inherits="ASPHelloWorld.HelloWorld"%>

This statement describes certain page level attributes for this aspx file. ASP .NET introduces a new syntactical construct <%@ ... %> which is used for specifying attributes. Every aspx file will have a statement similar to this that describes attributes such as the class that contains the event handler code, the name of the file containing the code, the language etc. This is necessary because ASP .NET cleanly distinguishes the presentation from the code. The aspx file only contains the HTML tags and server controls, while all the code needed to process the events that are fired by these controls are contained in a separate file. This allows the separation of effort between graphic designers who could be building beautiful pages and software engineers who could be writing beautiful code. The current ASP model mixes the HTML tags and controls with code, and anyone trying to read, maintain, or debug a 5000 line ASP file can attest to this.

There are too many ASP .NET attributes that can be covered here, so I will concentrate on some of the most important ones.

  • Language: This tells the ASP .NET compiler (yes! ASP .NET is compiled) that the language used is VB. Currently ASP .NET supports VB, JavaScript and C#.
  • CodeBehind: Determines the file that contains the event handling code for this aspx file.
  • Inherits: Determines the class that will contain methods to handle events on this page.
  • AspCompat: Determines whether this page is backward compatible with ASP.
  • Buffer: Determines whether page level buffering is enabled.
  • EnableSessionState: Determines whether SessionState is enabled.
  • ErrorPage: Determines the URL to be redirected to in the event of an unhandled exception.

ASP .NET Controls

These controls form the heart of ASP .NET. These are rich server side controls that can be used to build a powerful UI on the web similar to Windows based user interfaces.

<asp:label id=lblName runat="server">Please enter your name</asp:label>
<asp:label id=lblHello runat="server"></asp:label>
<asp:textbox id=txtName runat="server"></asp:textbox>
<asp:button id=btnSubmit runat="server" Text="Submit"></asp:button>

As you can see in the code above, the HelloWorld example uses four ASP .Net controls. Note the "asp:" prefix for each control. This is what distinguishes ASP .NET controls from standard HTML controls. We use two labels to display static messages, a textbox to allow the user to input the name, and a button that will be used as a submit button. These server side controls fire events very similar to the way windows controls fire events in a VB 6.0 program. These events can be trapped and code can be written to take action depending on what event is fired for what control. This offers much more functionality and flexibility that standard HTML controls. Currently ASP .NET supports the following types on server side controls:

  • <asp:button>
  • <asp:imagebutton>
  • <asp:linkbutton>
  • <asp:hyperlink>
  • <asp:textbox>
  • <asp:checkbox>
  • <asp:radiobutton>
  • <asp:image>
  • <asp:label>
  • <asp:panel>
  • <asp:table>

HelloWorld.vb Details

This file contains the code that supports the ASP .NET controls from the HelloWorld.aspx file. This code is identical to VB code, in fact it is VB code. Lets start with some code excerpts, again I would recommend you to have VS .NET open and the project loaded and have the code in its entirety.

Importing Namespaces

Imports System
Imports System.ComponentModel.Design
Imports System.Data
Imports System.Drawing
Imports System.Web
Imports System.Web.SessionState
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.HtmlControls
Imports Microsoft.VisualBasic

.NET introduces the concept of namespaces. Namespaces are essentially a collection of types and functionality. VB .NET introduces the Imports statement that is used to references assemblies outside your project. Most of the namespaces that are imported here are from the System namespace, but you could import any namespace as long as it lives in a public assembly. Importing a namespace is similar to adding a reference to a DLL in VB 6.0. It allows you to access the public elements (classes, functions, methods, etc) in that namespace. In our example, VS .NET automatically imports these namespaces to add support for Web Controls. You could easily add to this default list. For example, if you wanted to add XML manipulation support to your code, you can add the "Imports System.XML" line to your code.

HelloWorld Class

Public Class HelloWorld

    Inherits System.Web.UI.Page
    Protected WithEvents lblName As System.Web.UI.WebControls.Label
    Protected WithEvents btnSubmit As System.Web.UI.WebControls.Button
    Protected WithEvents txtName As System.Web.UI.WebControls.TextBox
    Protected WithEvents lblHello As System.Web.UI.WebControls.Label

    Public Sub btnSubmit_Click(ByVal sender As Object, ByVal e As 
        txtName.Visible = False
        lblName.Visible = False
        btnSubmit.Visible = False
        lblHello.Text = "Hello World (by " + txtName.Text + ")"
        lblHello.Visible = True
    End Sub
    Protected Sub WebForm1_Load(ByVal Sender As System.Object, ByVal e
                                                   As System.EventArgs)
        ' Evals true first time browser hits the page
        If Not IsPostback Then
            lblHello.Visible = False
        End If
    End Sub
End Class

VB .NET is a purely object oriented language. (Of course, you could still write non-OO code and not use the OO features that VB .NET provides, but that defeats the purpose). Thus, all the code in the above figure resides in a class definition. We declare a public class named HelloWorld that forms the backbone of our HelloWorld.aspx page. All the code behind an ASP .NET page is derived from the System.Web.UI.Page class, which contains the framework code for ASP .NET pages.

The four controls that are used on this page as defined as protected members of this class and the type of each controls is referenced from the System.Web.UI.WebControls namespace. The WithEvents keyword is used to specify that the object variables will respond to triggered events. In addition to these data members, you could add any data members that you may want to and specify the access modifiers (public, private, protected) for these data members.

The crux of the logic in an ASP .NET page will live in the event handling code for one or more server side controls. In our trivial example, we handle two events. The first event is for the page load in which we simply hide the label that will be used to display the Hello World message. When the user clicks on the Submit button, this will fire the event handled by the btnSubmit_Click method. In this method, we simply read the value entered in the textbox and display the Hello World message. We also hide some of the controls that are no longer needed. This is all the code that is necessary to support our Hello World sample.

Config.web Details

With ASP .NET, Microsoft introduces the notion of a human readable and modifiable configuration file for Web Applications. Those of you who have dealt with the IIS Metabase know that maintaining and modifying configuration wasn't exactly a breeze. ASP .NET introduces an XML file based configuration scheme, which is extremely powerful. The amount of details in the file warrants a whole new article, so I will focus only on some of the settings that are generated by VS .NET by default.

<compliation  debugmode="true" />
<customerrors mode="Off"  />

These are some of the default settings generated by VS .NET.

Compilation Mode
This settings tells the.NET compilers to generate debug information for the .aspx files. This is usually set to True in the development cycle, but once the application is moved over to Production, this should be set to false. Turning off this setting greatly improves the runtime performance of the system.
Custom Errors
ASP .NET introduces a declarative way of exception handling. By turning on CustomErrors, it is possible for ASP .NET to redirect the page to an error page whenever an unhandled exception occurs. Further, it is possible to define separate custom error pages for each HTTP error code that could occur. This is a very powerful feature that can avoid ugly errors being shown to the user.
Those of you who have tried debugging traditional ASP programs probably used more Response.Write statements than you cared to. ASP .NET introduces an elegant way of adding trace/debug information that is consistent and configurable. By turning on Trace in the Config.web file, it is possible to have Trace statements throughout the code that can be turned on or off by this switch. Further, you can determine where the trace output is displayed and have levels of tracing such as Fatal or Informational.
Session State
There have been so many occasions where I wished I could use the ASP Session variables, only to realize that the application will be running on a WebFarm without server affinity. In these cases, you end up not using the ASP Session, or you come up with your own implementation of session state. ASP .NET introduces a new way of handling Session data. You could use session the way it is used currently, or you could use a separate process (on the same machine or a separate machine) to store session data. You could even persist session data in a database. Again, this is entirely declarative and you don't have to change a single line of code to support this. This is a very powerful way to handle session data without having to implement a custom implementation.


When I wrote my first Hello World in C, I used the following code

#include <stdio.h>

int main ()
	printf ("Hello World");
	return 1;

My next Hello World was in C++, which took a few more lines, and then I moved over to Windows Programming in SDK, Windows Programming in MFC, COM Programming, COM Programming in ATL and slowly the complexity of the Hello World programs kept increasing. The same holds true for the Hello World that I wrote for ASP .NET. As you can see from the above code, the code needed to write a Hello World example takes far more than 7 lines. However, most of the code that is present is to support the framework and the plumbing needed to build complex real world applications. This is certainly true for ASP .NET, which is a huge huge improvement over traditional ASP, and Microsoft has brought VB-like development to the web. In future articles, I will dig deeper into the guts of ASP .NET.

Happy .Netting !

Additional Information:

  • 0
  • 0
  • 0
  • 一键三连
  • 扫一扫,分享海报

<p> <span style="font-size:14px;color:#337FE5;">【为什么学爬虫?】</span> </p> <p> <span style="font-size:14px;">       1、爬虫入手容易,但是深入较难,如何写出高效率的爬虫,如何写出灵活性高可扩展的爬虫都是一项技术活。另外在爬虫过程中,经常容易遇到被反爬虫,比如字体反爬、IP识别、验证码等,如何层层攻克难点拿到想要的数据,这门课程,你都能学到!</span> </p> <p> <span style="font-size:14px;">       2、如果是作为一个其他行业的开发者,比如app开发,web开发,学习爬虫能让你加强对技术的认知,能够开发出更加安全的软件和网站</span> </p> <p> <br /> </p> <span style="font-size:14px;color:#337FE5;">【课程设计】</span> <p class="ql-long-10663260"> <span> </span> </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 一个完整的爬虫程序,无论大小,总体来说可以分成三个步骤,分别是 </p> <ol> <li class="" style="font-size:11pt;color:#494949;"> 网络请求模拟浏览器的行为从网上抓取数据。 </li> <li class="" style="font-size:11pt;color:#494949;"> 数据解析将请求下来的数据进行过滤,提取我们想要的数据。 </li> <li class="" style="font-size:11pt;color:#494949;"> 数据存储将提取到的数据存储到硬盘或者内存中。比如用mysql数据库或者redis等。 </li> </ol> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 那么本课程也是按照这几个步骤循序渐进的进行讲解,带领学生完整的掌握每个步骤的技术。另外,因为爬虫的多样性,在爬取的过程中可能会发生被反爬、效率低下等。因此我们又增加了两个章节用来提高爬虫程序的灵活性,分别是 </p> <ol> <li class="" style="font-size:11pt;color:#494949;"> 爬虫进阶包括IP代理,多线程爬虫,图形验证码识别、JS加密解密、动态网页爬虫、字体反爬识别等。 </li> <li class="" style="font-size:11pt;color:#494949;"> Scrapy和分布式爬虫Scrapy框架、Scrapy-redis组件、分布式爬虫等。 </li> </ol> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 通过爬虫进阶的知识点我们能应付大量的反爬网站,而Scrapy框架作为一个专业的爬虫框架,使用他可以快速提高我们编写爬虫程序的效率和速度。另外如果一台机器不能满足你的需求,我们可以用分布式爬虫让多台机器帮助你快速爬取数据。 </p> <p style="font-size:11pt;color:#494949;">   </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> 从基础爬虫到商业化应用爬虫,本套课程满足您的所有需求! </p> <p class="ql-long-26664262" style="font-size:11pt;color:#494949;"> <br /> </p> <p> <br /> </p> <p> <span style="font-size:14px;background-color:#FFFFFF;color:#337FE5;">【课程服务】</span> </p> <p> <span style="font-size:14px;">专属付费社群+定期答疑</span> </p> <p> <br /> </p> <p class="ql-long-24357476"> <span style="font-size:16px;"><br /> </span> </p> <p> <br /> </p> <p class="ql-long-24357476"> <span style="font-size:16px;"></span> </p>
套餐中一共包含5门程序员必学的数学课程(共47讲) 课程1《零基础入门微积分》 课程2《数理统计与概率论》 课程3《代码学习线性代数》 课程4《数据处理的最优化》 课程5《马尔可夫随机过程》 哪些人适合学习这门课程? 1)大学生,平时只学习了数学理论,并未接触如何应用数学解决编程问题; 2)对算法、数据结构掌握程度薄弱的人,数学可以让你更好的理解算法、数据结构原理及应用; 3)看不懂大牛代码设计思想的人,因为所有的程序设计底层逻辑都是数学; 4)想学习新技术,如人工智能、机器学习、深度学习等,这门课程是你的必修课程; 5)想修炼更好的编程内功,在遇到问题时可以灵活的应用数学思维解决问题。 在这门「专为程序员设计的数学课」系列课中,我们保证你能收获到这些: ①价值300元编程课程大礼包 ②应用数学优化代码的实操方法 ③数学理论在编程实战中的应用 ④程序员必学的5大数学知识 ⑤人工智能领域必修数学课 备注此课程只讲程序员所需要的数学,即使你数学基础薄弱,也能听懂,只需要初中的数学知识就足矣。 如何听课? 1、CSDNapp我的-我的内容库-我的课程 2、程序员学院app我的-学习 3、pc端CSDN官网https://edu.csdn.net/ 我的订阅-收费课 购课后如何领取免费赠送的编程大礼包? 购课后,添加助教微信 csdn590,按提示领取大礼包
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
钱包余额 0