A collection of ASP.net basic Learning notes _ practical Tips

Source: Internet
Author: User
Tags class definition form post html form http request httpcontext iis socket what is asp

It is worth collecting the ASP.net basic study notes, share to everybody.

1. Introduction browser-Server B/S browsing

Browser and server interaction between the formation of Internet B/S mode

For HTML upload server to Server Software (IIS) server software directly read static page code, and then return to the browser

For the ASPX delivery server to the Server Software (IIS) IIS found that it can not handle ASPX files, go to the map table to find a response in the suffix name of the handler (ISAPI, Server extender) question: How IIS invoke the extensible program? A: An Extender is the first to implement code in accordance with the excuse provided by IIS, so IIS knows how to invoke it.


2. What is asp.net

!asp.net is a Dynamic Web page technology that runs. NET code on the server side, generates HTML dynamically, and then responds to a browser

* Note that the main operation is the server to operate, the browser is only transfer instructions

! You can use JavaScript, Dom to do a lot of work on the browser side, but there are a lot of work can not be browsed to finish, such as storing data, access to the database is not complex business logic operations, security requirements of high logic operations.

! Server-side controls and HTML control generation relationships: You can use server-side controls in ASPX pages to simplify openness. However, browsers only recognize HTML, so the server-side controls in the page are assembled into the corresponding HTML control code strings when the page containing the service-side control is requested, such as a TextBox: <input type= "text"/>

!asp.net:ashx (General handler) (fastest on the server), WEBFORM,WVC3 (Model, View, Controler)

! Server control is not a new control, the browser-side is still generated HTML tags, server-side controls, although easy to use, but also has drawbacks, is not where it is good to be used, specifically, later.

Common documents in 3.aspx.net (emphasis)

The first small example: Dynamic login Program

  public void ProcessRequest (HttpContext context) {
  string modelpath = context. Server.MapPath ("loginmodel.htm");
  String htmlsendback = System.IO.File. ReadAllText (Modelpath);
  Context. Response.ContentType = "Text/plain";
  Context. Response.Write (htmlsendback);
  if (!string. IsNullOrEmpty (context. request.form["Txtname"])
  {
   if (context). request.form["txtname"] = = "Zhu" && context
    . request.form["Txtpassword"] = = "123")
   {context
    . Response.Write ("Login succeeded!");
   else context
    . Response.Write ("Logon failed!");
  }
 

4. General processing procedure (HttpHandler)

I. GENERAL processing procedures (HttpHandler):

is a class that implements the System.Web.IHttpHandler special interface.

Any class that implements the IHttpHandler interface can be a target program for an external request: (All classes that do not implement this interface are not requested by the browser)

Two. It is invoked and started by a server that supports asp.net. A HttpHandler program handles access requests for one or a set of URL addresses that it corresponds to, and accepts access information from clients and generates corresponding content.

Three. We can generate browser code to return to the client browser by creating a HttpHandler program of our own

Four. The HttpHandler program can accomplish most tasks that ordinary class programs can accomplish:

1. The Lake area client submits data and URL parameters via HTML form form forms

2. Create response information content to the client

3. Access to server-side file systems

4. Connecting to databases and developing database based applications

5. Call Other Classes

5. Request the corresponding process

1. Users in the browser address bar input: http://localhost:80777/FirstShower.ashx
2. The server receives the user's request, discovers is requests. ashx file, then the request to the framework execution, the FW finds the corresponding file First.ashx, executes the generated string (usually Html+css+javascript format) to return to the browser
3. The browser receives the data returned by the server and executes it according to the HTTP syntax, which is displayed to the user in an interface manner. (At this point, if you have external files in code such as HTML, send the corresponding file data for the individual request server again)

6.HTTP Request detailed diagram

7.ashx? -httphandler (General handler)

IHttpHandler hander = new Page class ();
Hander. ProcessRequest (); Called methods in the Page class, which is the advantage of the interface

ContentType markup returns the language of an object's interpretation in a Web page

Text/html using HTML language translation

is to set the server to send the response message of the ContentType property, the browser based on this property content, using a different method of processing [response message]

8. Compile Process

1. Each request will create a httpworkerrequest and HttpApplication
2.HttpWorkerRequest contains the data in each request message.
The 3.HttpApplication object contains the code to be executed for each request.
4. To create a separate HttpApplication object for each request, all running procedures for this request are completed in this object

Factory Understanding:: HttpApplication pool, every time httpapplicationfectory in this pool to find there is no idle HttpApplication object, if there is, directly out of use, did not create a new use.

What the server does: accept the browser request, create the object of the page class, implement the interface, call the inside method, and return the corresponding Dongdong

HttpRuntime inside, by this class, handles all the requests, it works

1. Analyze the request message and encapsulate the message data into a class called HttpWorkerRequest object
2. Create the HttpContext object, which is the context of the current request, containing all parameter data for processing the request, the most important of which is the HttpRequest and HttpResponse two classes (easy to value)
3.HttpRequest contains all the request information, which originates from the Httpworkrequest object, which contains attributes: Form (client connection data) QueryString (client URL parameter)
The 4.HttpResponse contains a FileStream object that is used to save data that is output to the browser during the execution of the page class.
5. Create the corresponding property in the HttpApplication class object by calling a static method of the Httpapplicationfectory class
6. Because in HttpApplication to run the ProcessRequest method in the requested page class object, the HttpContext object needs to be passed into the HttpApplication (IHttpHandler hander = Create the requested page class object by reflection?

Execute the HttpApplication ProcessRequest method (you can consider the execution of this method as a pipe) in this method, sequentially executes 19 delegate events in sequence

• Create the object of the requested page class at the 8th event
• ProcessRequest method of creating page classes in between 11 and 12

9. How does the server receive and send data?

HTTP Request Response

9.1 Request (HttpRequest) & Response (HttpResponse)

One, the browser submits the data way
1 Forms (data hidden in the style of the request report, format txtname=jamws&txtpwd=123)

<form action= "Login.ashx" method= "POST" >
    <input type= "text" name= "txtname"/> <input "type=" 
    Password "name=" txtpwd "/>
 </form>

2 Address bar URL parameters (same as the form's Get method): Key values for browser request Properties Http://127.0.0.1/login.ashx?txtname 1=jordan&txtpwd 1=123

Second, how does the server get the data submitted by the browser?
1 Gets the form data context. request.form["Txtname"]
2 Get URL parameter: Context. request.querystring["Txtname1"]

Third, how the server output parameters to the browser

Context. Response.Write ("I am outputting data from the server to the browser!");

When the user clicks the Submit button in the browser, the browser automatically submits the value of the control with name in the form to the server as an [HTTP request style] to assign a value to the string.

The request itself can also be viewed as a client-submitted parameter.
Request.Form contains only data that the client submits over the post
Reuqest.querystring contains only data that the client submits over the Get method

Get: Fetch, take--when the browser sends the request message to get the data from the server, it is used
Post: Pass, land, send the past. --When the browser sends the request message pass parameter past, use post


public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "text/html";
  System.Text. StringBuilder sbhtml = new System.Text.StringBuilder (); Sbhtml.append (" 

9.2 Request (HttpRequest) Important member

The redirection schematic is as follows:

------------------the user control data for the impersonated Wubform is persisted------------------

  public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "text/html"; String strNum1 = context.
  request.form["TxtNum1"]; String strNum2 = context.
  request.form["TxtNum2"];
  Determine if the format is correct string result = "0";
  int NUM1 = 0, num2 = 0; if (!string. IsNullOrEmpty (STRNUM1) &&! String. IsNullOrEmpty (strNum2)) {if (int). TryParse (STRNUM1, out NUM1) && Int. TryParse (strNum2, out num2)) {result = (num1+num2).
   ToString ();
   else {result = "input format error"; }} system.text.
  StringBuilder sbhtml = new System.Text.StringBuilder (); Sbhtml.append ("<! doctype> 

------------------analog WebForm return checking mechanism------------------ 

  public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "text/html"; String strNum1 = context.
  request.form["TxtNum1"]; String strNum2 = context.
  request.form["TxtNum2"];
  Determine if the format is correct string result = "0";
  int NUM1 = 0, num2 = 0; If a hidden field is included, the add operation is performed if (!string). IsNullOrEmpty (context. request.form["Hidispostback"]) {if (!string). IsNullOrEmpty (STRNUM1) &&! String. IsNullOrEmpty (strNum2)) {if (int). TryParse (STRNUM1, out NUM1) && Int. TryParse (strNum2, out num2)) {result = (NUM1 + num2).
    ToString ();
    else {result = "input format error"; }} system.text.
  StringBuilder sbhtml = new System.Text.StringBuilder (); Sbhtml.append ("<! doctype> 

----------------------------Object-oriented calculator----------------------------

 ---------------------------------class definition--------------------------------------------///<summary>///a calculator class/
 </summary> public class Class1 {//first operand public int num1 {get; set;}
 Second operand public int num2 {get; set;}
 Operator public string calculatechar{get; set;}
 The result is public string results {get; set;} Public Class1 () {}///<summary>///calculation results///</summary>///<param name= "A" > First operand &LT;/PARAM&G
 T <param name= "B" > second operand </param>///<param name= "oper" > operator </param> public void Getresu
  LT (int A, int b, string oper) {this.num1 = A;
  this.num2 = b;
  This.calculatechar = oper; Switch (this. Calculatechar) {case ' + ': result = (NUM1 + num2).
    ToString ();
   Break Case "-": result = (num1-num2).
    ToString ();
   Break Case "*": result = (NUM1 * num2).
    ToString ();
   Break Case "/": result = (num1/num2).
    ToString ();
  Break }
    }
}
 
//------------------------------------------------------Page class----------------------------------------------------------public Class _07calculatefour:ihttphandler {public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "text/html";
  Instantiate a Calculator object Class1 CALCU = new Class1 (); String strNum1 = context.
  request.form["TxtNum1"]; String strNum2 = context.
  request.form["TxtNum2"]; String stroper = context.
  request.form["Optionoper"];
  int NUM1 = 0;
  int num2 = 0; if (!string. IsNullOrEmpty (context. request.form["Hidispostback"]) {//Analog return visit if (!string). IsNullOrEmpty (STRNUM1) &&! String. IsNullOrEmpty (strNum2)) {//judged to be an empty if (int. TryParse (STRNUM1, out NUM1) && Int. TryParse (strNum2, out num2)) {//Judgment format CALCU.
    GetResult (NUM1, num2, Stroper);
    else {Calcu.result = "incorrect parameter format"; }} system.text.
  StringBuilder sbhtml = new System.Text.StringBuilder (); Sbhtml.append ("<! DOCTYPE > 

10. Note that the content of the submission form

* Only for input, textarea, select three types of labels, only input (text box/checkbox, etc.) users can fill in the value,<label>,<p>,<font> and other labels only provide display, There is no need to submit to the server.
• Only value attributes will be submitted to the server, the input tag for example, the input label has title,type,disabled properties, but these properties are for display, users can not modify, only the Value property is the user input attributes, Therefore, only values for the Value property are committed to the server
• The label must set the Name property. When learning DOM, we know that if you manipulate the tag through JavaScript, you must set the id attribute for the tag. If you want to submit the Value property of the label to the server, you must set the Name property for the label, submit to the server with a "Name=value" key-value pair to the server, with & separated, in addition to the radio button and other minority tags, you can repeat, other name cannot repeat. Name is for the server, the ID is for the DOM, for RadioButton, the name is a group, and the value of the selected RadioButton is committed to the server.
• If the disabled property of the control is set, the browser will not give the data to the server
• Placed in the form label, only the form tag can be submitted to the server, the form of input and other tags are ignored.

11. Use template to clear code, using Virtual template page

• Use hidden fields to simulate IsPostBack, <input type= "hidden" name= "Hidispostback" value= "true"/>
• In the template page, it is worth the time to modify, you can use the placeholder, after that, direct replacement can be, using the form of {name}

public class _08cal:ihttphandler {public void ProcessRequest (HttpContext context) {context.
  Response.ContentType = "text/html"; --------------------Read HTML content template----------------------//obtain physical path based on virtual path string path = Context. Server.MapPath ("calculatemodel.htm"); Here carefully remember string strhtml = System.IO.File.ReadAllText (path); Also remember here//------------------get the content submitted by the browser---------------------------string strNum1 = context.
  request.form["TxtNum1"]; String strNum2 = context.
  request.form["TxtNum2"];
  int NUM1 = 0;
  int num2 = 0;
  string result = ""; if (!string. IsNullOrEmpty (context. request.form["Hidispostback"]) {if (!string). IsNullOrEmpty (STRNUM1) &&!string. IsNullOrEmpty (strNum2)) {if (int). TryParse (STRNUM1, out NUM1) && Int. TryParse (strNum2, out num2)) {result = (NUM1 + num2).
    ToString ();
    else {result = "input format error"; }}//-------------------------output HTML to browser------------------------//String substitution, assign StrhtML = Strhtml.replace ("{NUM1}", Num1.) ToString ()). Replace ("{num2}", num2.) ToString ()). Replace (' {result} ', result.
  ToString ()); Context.
 Response.Write (strhtml);
  public bool IsReusable {get {return false;

 }
 }

}
---------------------------------Template page display---------------------------------------
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
< html>
< head>
 < title> calculator </title >
 
 

12. How to submit a form to get and post

The amount of data that get is passed is limited, the amount of data sent by post is not limited
Post causes a refresh resubmit form problem, and get no such problem, you can use the address bar to reset the problem
Get way URL data format,? Back & Split, URLs with Chinese characters will be URL-coded

form fields can be passed only if name is set, get see clearly, submit if there is value, will also pass

13. Self-increasing data

HTTP is stateless, each time the browser requests the server's page class, the server creates an object of the class, invokes the method inside it, and finally returns the output to the browser, and then the object destroys the disconnected
• Browsers and servers are not aware of each other

Connection:keep-alive tells the server browser that the long connection short connection you want to use is equivalent to a one-time connection

Disadvantage of short connection: Although the customer only wants to visit a page, HTML still sends many new connection requests to the browser, establishes many new connections, consumes the time resources of both sides.

HTTP Short Connection: The server closes the current connection (socket) immediately after each response to a request from the browser.

Long connection: The server will not immediately close the connection channel (socket) after sending the data, but will wait for a period of time (2 seconds), two seconds, if the same browser to send the request again, then continue to use this connection channel to output data to the browser, and then log Between, until 2 seconds later, no new requests come in, then the server closes the connection channel

Counter-compiling tools to keep looking, to understand the principle, operating mechanism---cattle

General handler _ simple request, about contenttype, get URL parameter (http parameter get/post transfer essence). (The principle of the request process, the principle of the overall request process, the page compiles the process), requests the data and accepts the data as well as the directional principle, simulates the WebForm return inspection mechanism, simulates wubform the user control data maintains, the self increases (solves HTTP the stateless), the login process

The next study:

Addition Calculator, add and remove check, build three-tier architecture, list and delete, delete information function, new

Upload a single file, generate thumbnails, general processing program output picture (simple verification code picture), output watermark picture, near download, review summary.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.