ASP.NET Tutorial/Page Lifecycle/Response

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Adding a cache dependency in ASP.NET

   <source lang="csharp">

<%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html>

  <head>
     <title>Adding a cache dependency in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.AddCacheItemDependencies("Key1")
           myMessage.Text = DateTime.Now()
        End Sub
        Sub Button1_Click(sender As Object, e As EventArgs)
           Cache("Key1") = "foo"
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="myMessage" runat="server"/>
     <asp:button id="Button1" text="Change Key 1" onClick="Button1_Click" runat="server"/>
  </form>

</body> </html></source>


Display all controls on a page

   <source lang="csharp">

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="ControlTree" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head >

   <title>Controls</title>

</head> <body>

       This is static HTML (not a web control).
   <form id="Controls" runat="server">
           <asp:panel id="MainPanel" runat="server" Height="112px">
           <asp:Button id="Button1" runat="server" Text="Button1"/>
           <asp:Button id="Button2" runat="server" Text="Button2"/>
           <asp:Button id="Button3" runat="server" Text="Button3"/>
           <asp:Label id="Label1" runat="server" Width="48px">
             Name:</asp:Label>
           <asp:TextBox id="TextBox1" runat="server"></asp:TextBox>
           </asp:panel>
           <asp:Button id="Button4" runat="server" Text="Button4"/>
   
   </form>
       This is static HTML (not a web control).

</body> </html> File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class ControlTree : System.Web.UI.Page {

 private void Page_Load(object sender, System.EventArgs e)
 {
   DisplayControl(Page.Controls, 0);
 }
 private void DisplayControl(ControlCollection controls, int depth)
 {
   foreach (Control control in controls)
   {
     Response.Write(new String("-", depth * 4) + "> ");
     Response.Write(control.GetType().ToString() + " - " + control.ID + "
"); if (control.Controls != null) { DisplayControl(control.Controls, depth + 1); } } }

}</source>


Displaying the HTTP headers collection in ASP.NET

   <source lang="csharp">

<html>

  <head>
     <title>Submit a named parameter via POST</title>
  </head>

<body>

  <form id="form1" action="NextPage.aspx" method="POST">

Name:

     <input type="text" name="name">
     <input type="submit">
  </form>

</body> </html>

File: NextPage.aspx <%@ Page Language="vb" %> <html>

  <head>
     <title>Displaying the HTTP headers collection in ASP.NET</title>
  </head>

<body>

<% Select Case Request.HttpMethod

  Case "POST"
     Response.Write("POST requests not allowed!
") Response.End Case "HEAD" Response.Write("HEAD requests not allowed!
") Response.End Case "GET" "Process request Response.Write("GET requests are allowed!
") Case Else Response.Write("Unknown request: not allowed!
") Response.End

End Select %>

</body> </html></source>


Displaying URL information in ASP.NET

   <source lang="csharp">

<html>

  <head>
     <title>Submit a named parameter via POST</title>
  </head>

<body>

  <form id="form1" action="NextPage.aspx" method="POST">

Name:

     <input type="text" name="name">
     <input type="submit">
  </form>

</body> </html> File: NextPage.aspx <%@ Page Language="vb" %> <html>

  <head>
     <title>Displaying URL information in ASP.NET</title>
  </head>

<body>

<% Dim myUri As Uri myUri = Request.Url Response.Write("Current request URL info ?

") Response.Write("Protocol: " & myUri.Scheme & "
") Response.Write("Port: " & myUri.Port & "
") Response.Write("Host Name: " & myUri.Host & "
") myUri = Request.UrlReferrer If Not (myUri Is Nothing) Then

  Response.Write("Referral URL info ? 

") Response.Write("Protocol: " & myUri.Scheme & "
") Response.Write("Port: " & myUri.Port & "
") Response.Write("Host Name: " & myUri.Host & "
") Response.Write("App Path: " & myUri.AbsolutePath & "
")

Else

  Response.Write("No referral URL info available.")

End If %>


</body> </html></source>


Response.AddCacheItemDependencies

   <source lang="csharp">

<%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html>

  <head>
     <title>Adding cache dependencies in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim myArrayList As New ArrayList
           myArrayList.Add("Key1")
           myArrayList.Add("Key2")
           Response.AddCacheItemDependencies(myArrayList)
           myMessage.Text = DateTime.Now()
        End Sub
        Sub Button1_Click(sender As Object, e As EventArgs)
           Cache("Key1") = "foo"
        End Sub
        Sub Button2_Click(sender As Object, e As EventArgs)
           Cache("Key2") = "bar"
        End Sub
     </script>
  </head>

<body>

  <form runat="server">
     <asp:label id="myMessage" runat="server"/>
     <asp:button id="Button1" text="Change Key 1" onClick="Button1_Click" runat="server"/>
     <asp:button id="Button2" text="Change Key 2" onClick="Button2_Click" runat="server"/>
  </form>

</body> </html></source>


Response.AddFileDependencies

   <source lang="csharp">

<%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html>

  <head>
     <title>Adding file dependencies in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim myArrayList As New ArrayList
           myArrayList.Add(Server.MapPath("dep.txt"))
           myArrayList.Add(Server.MapPath("dep1.txt"))
           Response.AddFileDependencies(myArrayList)
           myMessage.Text = DateTime.Now()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.AddFileDependency

   <source lang="csharp">

<%@ Page Language="vb" %> <%@ OutputCache Duration="300" VaryByParam="None" %> <html>

  <head>
     <title>Adding a file dependency in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.AddFileDependency(Server.MapPath("dep.txt"))
           myMessage.Text = DateTime.Now()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.AppendHeader

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Adding an HTTP Header in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.AppendHeader("Content-Type", "text/xml")
           myMessage.Text = Response.ContentType
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.AppendToLog

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Adding an HTTP Header in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.AppendToLog("Hello from Page_Load!")
           myMessage.Text = "myMessage written to IIS Log!"
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ApplyAppPathModifier

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Creating Absolute URLs for cookieless sessions in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim NewPath As String
           NewPath = Request.Url.Scheme & "://" & Request.Url.Host & _
              Response.ApplyAppPathModifier(Request.Url.AbsolutePath)
           myMessage.Text = "Modified Absolute URL = " & NewPath
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.BinaryWrite

   <source lang="csharp">

<%@ Page Language="vb" %> <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <%@ Import Namespace="System.IO" %> <html>

  <head>
     <title>Writing binary content in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim ConnStr As String
           ConnStr = "Data Source=(local)\NetSDK;"
           ConnStr &= "database=pubs;integrated security=true"
           Dim mySqlConn As New SqlConnection(ConnStr)
           mySqlConn.Open
           Dim SQL As String = "SELECT logo FROM pub_info WHERE pub_id = "0736""
           Dim mySqlCmd as New SqlCommand(SQL, mySqlConn)
           mySqlCmd.rumandType = CommandType.Text
           Dim Reader As SqlDataReader
           Reader = mySqlCmd.ExecuteReader()
           Dim ImageBytes() As Byte
           While Reader.Read()
              ImageBytes = Reader.Item(0)
           End While
           Response.ContentType = "image/bmp"
           Response.BinaryWrite(ImageBytes)
           Response.End()
           Reader.Close()
           mySqlConn.Close()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.BufferOutput

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Buffering Output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.BufferOutput = False
           Dim i As Integer
           For i = 1 To 50
              If (i > 10 And i < 30) Then 
                 Response.BufferOutput = True
              Else
                 Response.BufferOutput = False
              End If
              System.Threading.Thread.Sleep(500)
              Response.Write(".")
              myMessage.Text &= "."
              "Response.Flush
           Next
           Response.Write("</br>Done!</br>")
           myMessage.Text &= "</br>Done!</br>"
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.Charset

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Modifying character set in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.Charset = "Windows-1255"
           myMessage.Text = "Current character set is " & Response.Charset
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ClearContent

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Clearing buffered output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.Write("This content will not be seen.")
           Response.ClearContent()
           myMessage.Text = "Content written with Response.Write was cleared."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ClearHeaders()

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Clearing buffered output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.AppendHeader("Content-Type", "text/xml")
           Response.ClearHeaders()
           myMessage.Text = Response.ContentType
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ContentEncoding

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Displaying Encoding in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           myMessage.Text = "Current encoding is " & _
              Response.ContentEncoding.EncodingName & "</br>"
           myMessage.Text &= "Current encoding IANA name is " & _
              Response.ContentEncoding.WebName & "</br>"
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ContentType

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Response property example</title>
     <script runat="server">
        Sub Page_Load()
           Response.ContentType = "text/xml"
           myMessage.Text = "This page will be displayed as XML in " & _
              "Internet Explorer 5.0 or above."
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.End()

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Ending processing in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.Write("Hello, World!")
           Response.End()
           myMessage.Text = "Hello, World!"
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.Expires

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Cacheing Output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.CacheControl = "Public"
           Response.Expires = 2
           myMessage.Text = Now.ToString()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.ExpiresAbsolute

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Cacheing Output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.CacheControl = "Public"
           Response.ExpiresAbsolute = DateTime.Now.AddSeconds(30)
           myMessage.Text = Now.ToString()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.IsClientConnected

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Checking client connection status in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           If Response.IsClientConnected = False Then
              Response.End
           Else
           End If
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.Output

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Writing Output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim myWriter As System.IO.TextWriter
           myWriter = Response.Output
           myWriter.WriteLine("Hello, World!")
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.PICS

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Sending a PICS label in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim PICSLabel As String
           PICSLabel &= "(PICS-1.1 <http://www.java.ru> "
           PICSLabel &= "labels on " & Chr(34)
           PICSLabel &= "2001.08.01T06:00-0000" & Chr(34)
           PICSLabel &= " until " & Chr(34)
           PICSLabel &= "2002.02.28T23:59-0000" & Chr(34)
           PICSLabel &= " ratings (V 1 S 2 L 3 N 1))"
           Response.PICS(PICSLabel)
           myMessage.Text = PICSLabel
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.RemoveOutputCacheItem

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Removing cache items in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Cache("Key1") = "foo"
           Response.RemoveOutputCacheItem(Request.Path)
           If Not Cache("Key1") Is Nothing Then
              myMessage.Text = Cache("Key1")
           Else
              myMessage.Text = "Cache items for " & Request.Path & _
                 " removed."
           End If
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.StatusCode

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Sending status in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.StatusCode = 542
           Response.StatusDescription = "Server Error - The code is the answer."
           Response.End()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.SuppressContent

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Suppressing content in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.Write("Hello, World!")
           Response.SuppressContent = True
           If Response.SuppressContent Then Response.Close()
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.Write

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Writing character output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Dim MyChars(2) As Char
           Dim MyChar As Char
           MyChars(0) = "A"
           MyChars(1) = "B"
           MyChars(2) = "C"
           For Each MyChar in MyChars
              Response.Write(MyChar)
           Next
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Response.WriteFile

   <source lang="csharp">

<%@ Page Language="vb" %> <html>

  <head>
     <title>Writing a file to output in ASP.NET</title>
     <script runat="server">
        Sub Page_Load()
           Response.WriteFile("dep.txt")
        End Sub
     </script>
  </head>

<body>

  <asp:label id="myMessage" runat="server"/>

</body> </html></source>


Submit a named parameter via POST

   <source lang="csharp">

<html>

  <head>
     <title>Submit a named parameter via POST</title>
  </head>

<body>

  <form id="form1" action="NextPage.aspx" method="POST">

Name:

     <input type="text" name="name">
     <input type="submit">
  </form>

</body> </html> File: NextPage.aspx <%@ Page Language="vb" %> <html>

  <head>
     <title>Displaying a named request parameter in ASP.NET</title>
  </head>

<body>

<%

  Response.Write(Request("name") & "

") Request.SaveAs("C:\HTTPRequest.txt", True) Dim length As Integer length = Request.ContentLength Response.Write("Length of request was: " & length & " bytes.")

%>

</body> </html></source>


Use Response.Redirect to transfer to another aspx file (C#)

   <source lang="csharp">

File: Default.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Cookieless1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
                   <asp:HyperLink ID="lnkRedirect" 
                                  runat="server" 
                                  NavigateUrl="NextPage.aspx">Link with Relative Path</asp:HyperLink>
                   <asp:Button ID="cmdLink" runat="server" Text="Redirect with Relative Path" OnClick="cmdLink_Click"></asp:Button>
                   <asp:Button ID="cmdLinkAbsolute" runat="server" Text="Redirect with Absolute Path" OnClick="cmdLinkAbsolute_Click"></asp:Button>
   </form>

</body> </html>

File: Default.aspx.cs using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Cookieless1 : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
 {
   Session["test"] = "Test String";
   }
 protected void cmdLink_Click(object sender, EventArgs e)
 {
   Response.Redirect("NextPage.aspx");
 }
 protected void cmdLinkAbsolute_Click(object sender, EventArgs e)
 {
   string url = "http://" + Request.Url.Authority +
     Request.Url.Segments[0] + Request.Url.Segments[1] +
     "NextPage.aspx";
   Response.Redirect(url);
 }

}

File: NextPage.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="NextPage.aspx.cs" Inherits="Cookieless2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"

"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server">

   <title>Untitled Page</title>

</head> <body>

   <form id="form1" runat="server">
       <asp:Label ID="lblInfo" 
                  runat="server" 
                  Font-Bold="True" 
                  Font-Names="Verdana" 
                  Font-Size="Large"></asp:Label>
   </form>

</body> </html>

File: NextPage.aspx.cs

using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; public partial class Cookieless2 : System.Web.UI.Page {

   protected void Page_Load(object sender, EventArgs e)
   {
   if (Session["test"] != null)
   {
     lblInfo.Text = "Successfully retrieved " + (string)Session["test"];
   }
   else
   {
     lblInfo.Text = "Session information not found.";
   }
   }

}</source>


Use Response.Write to output data from a database

   <source lang="csharp">

<%@ Page Language="VB" AutoEventWireup="false"%> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body>

   Here comes the data!

<%

   Dim connect As New SqlConnection( _
    "Server=mycomp;UID=sa;password=password01;database=Dummies")
   connect.Open()
   Dim cmd As New SqlCommand( _
      "select nameid from names where first_name ="Jeff"", _
     connect)
   Dim id As Int32
   id = cmd.ExecuteScalar()
   connect.Close()
   Response.Write(id)

%>

   
How about that?

</body> </html></source>