ASP.NET Tutorial/Page Lifecycle/Request

Материал из .Net Framework эксперт
Версия от 12:00, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Displaying additional path information in ASP.NET

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Displaying additional path information in ASP.NET</title>
   </head>
<body>

<%
   Response.Write("File Path = " & Request.FilePath & "<br>")
   Response.Write("Path = " & Request.Path & "<br>")
   Response.Write("Additional Path Info = " & Request.PathInfo & "<br>")
   Response.Write("Physical Application Path = " & Request.PhysicalApplicationPath & "<br>")
   Response.Write("Physical Path = " & Request.PhysicalPath)
%>

</body>
</html>


Displaying the Request.FilePath property in ASP.NET

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Displaying the Request.FilePath property in ASP.NET</title>
   </head>
<body>

<%
   Dim fp As String
   fp = Request.FilePath
   Response.Write("The virtual path of the current request is: <strong>" & fp & "</strong>")
%>

</body>
</html>


Filtering the HTTP Request body using InputStream

<html>
   <head>
      <title>Submit a named parameter via POST</title>
   </head>
<body>
   <form id="form1" action="NextPage.aspx" method="POST">
      <h3>Name:</h3>
      <input type="text" name="name">
      <input type="submit">
   </form>
</body>
</html>
File: NextPage.aspx
<%@ Page Language="vb" %>
<%@ import namespace = "System.IO" %>
<html>
   <head>
      <title>Filtering the HTTP Request body using InputStream</title>
   </head>
<body>

<%
Dim intvar As Integer
intvar = Request.TotalBytes
Response.Write("The size of the current request body is: <br>")
Response.Write(intvar & " bytes.<br>")
Dim InStream As Stream
Dim iCounter, StreamLength, iRead As Integer
Dim OutString As String
Dim Found As Boolean
InStream = Request.InputStream
StreamLength = CInt(InStream.Length)
Dim ByteArray(StreamLength) As Byte
Trace.Write("StreamLength", StreamLength)
iRead = InStream.Read(ByteArray, 0, StreamLength)
For iCounter = 0 to StreamLength - 1
   If Found = True Then
      OutString = OutString & Chr(ByteArray(iCounter))
   End If
   If Chr(ByteArray(iCounter)) = "A" Then
      Trace.Write("Found", "Found an "A"")
      Found = True
      OutString = OutString & Chr(ByteArray(iCounter))
   End If
   Trace.Write("Loop Number", iCounter)
   Trace.Write("CurrentChar", Chr(ByteArray(iCounter)))
Next iCounter
Response.Write("Output: " & OutString)
%>

</body>
</html>


Get browser information

<%@ Page EnableViewstate="False" %>
<script language="VB" runat="server">
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)
  Dim s As String
  s &= "ActiveXControls=" & Request.Browser.ActiveXControls & "<br>"
  s &= "AOL=" & Request.Browser.AOL & "<br>"
  s &= "BackgroundSounds=" & Request.Browser.BackgroundSounds & "<br>"
  s &= "Beta=" & Request.Browser.Beta & "<br>"
  s &= "Browser=" & Request.Browser.Browser & "<br>"
  s &= "CDF=" & Request.Browser.CDF & "<br>"
  s &= "ClrVersion=" & Request.Browser.ClrVersion.ToString & "<br>"
  s &= "Cookies=" & Request.Browser.Cookies & "<br>"
  s &= "Crawler=" & Request.Browser.Crawler & "<br>"
  s &= "EcmaScriptVersion=" & Request.Browser.EcmaScriptVersion.ToString & "<br>"
  s &= "Frames=" & Request.Browser.Frames & "<br>"
  s &= "JavaApplets=" & Request.Browser.JavaApplets & "<br>"
  s &= "JavaScript=" & Request.Browser.JavaScript & "<br>"
  s &= "MajorVersion=" & Request.Browser.MajorVersion & "<br>"
  s &= "MinorVersion=" & Request.Browser.MinorVersion & "<br>"
  s &= "MSDomVersion=" & Request.Browser.MSDomVersion.ToString & "<br>"
  s &= "Platform=" & Request.Browser.Platform & "<br>"
  s &= "Tables=" & Request.Browser.Tables & "<br>"
  s &= "Type=" & Request.Browser.Type & "<br>"
  s &= "VBScript=" & Request.Browser.VBScript & "<br>"
  s &= "Version=" & Request.Browser.Version & "<br>"
  s &= "W3CDomVersion=" & Request.Browser.W3CDomVersion.ToString & "<br>"
  s &= "Win16=" & Request.Browser.Win16 & "<br>"
  s &= "Win32=" & Request.Browser.Win32 & "<br>"
  
  Label.Text = s
End Sub
</script>
<html>
  <body>
    <form runat="server">
      <b>Browser Capabilties:</b><br>
      <asp:Label Runat="server" ID="Label" />
    </form>
  </body>
</html>


Get Request.UserLanguages

<%@ Page Language="VB" %>
<%@ Import Namespace="System.Globalization" %>
<script runat="server">
   sub Page_Load(Sender as Object, e as EventArgs)
      dim strLanguage as string = Request.UserLanguages(0).ToString
      
      lblMessage.Text = "Primary language: " & strLanguage & "<br>"
      
      dim objCulture as new CultureInfo(strLanguage)
      lblMessage.Text += "Full name: " & objCulture.EnglishName & "<br>"
      lblMessage.Text += "Native name: " & objCulture.NativeName & "<br>"
      lblMessage.Text += "Abbreviation: " & objCulture.ThreeLetterISOLanguageName & "<br>"
      lblMessage.Text += "Current Time: " & DateTime.Now.ToString("D", objCulture) & "<br>"
      lblMessage.Text += "Parent: " & objCulture.Parent.EnglishName & "<br>"
      
   end sub   
</script>
<html><body>
   <b>Your user information:</b> 
   <asp:Label id="lblMessage" runat="server"/>
</body></html>


Getting cookie values

<%@ Page Language="vb" Explicit="False" Strict="False" %>
<html>
   <head>
      <title>Getting cookie values in ASP</title>
   </head>
<body>

<%
For Each strKey In Request.Cookies
   Response.Write (strKey & " = " & Request.Cookies(strKey).Value & "<BR>")
   If Request.Cookies(strKey).HasKeys Then
      For Each strSubKey In Request.Cookies(strKey).Values
         Response.Write ("->" & strKey & "(" & strSubKey & ") = " & _
            Request.Cookies(strKey)(strSubKey).ToString() & "<BR>")
      Next
   End If
Next
%>

</body>
</html>


Request.Cookies

<script language="C#" runat="server" trace="true" >
protected void Page_Load(object o, EventArgs e) {
HttpCookie outbound = new HttpCookie("MyCookie");
HttpCookie inbound = Request.Cookies["MyCookie"];
if(inbound != null) {
    outbound.Value = (Int32.Parse(inbound.Value) + 1).ToString();
    theLabel.Text = inbound.Value;
}
else {
    outbound.Value = "1";
}
Response.Cookies.Add(outbound);
}
</script>
<asp:label runat="server" id="theLabel" Text="no cookie value received" />


Request.Headers

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Displaying the HTTP headers collection in ASP.NET</title>
   </head>
<body>

<%
   Response.Write(Request.Headers)
   Request.SaveAs((Request.PhysicalApplicationPath & "HTTPRequest.txt"), True)
   Request.SaveAs((Request.PhysicalApplicationPath & "HTTPRequest_NoHeaders.txt"), False)
%>

</body>
</html>


Request.QueryString

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Search" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Search Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <h1>Search</h1>
    You have successfully redirected to the search page.
    
    Your search string was <em><asp:Label ID="labSearch" runat="server" /></em>
    </div>
    </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 Search : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       labSearch.Text = (string)Request.QueryString["search"];
    }
}


Request.ServerVariables

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Request property example</title>
      <script runat="server">
         Sub Page_Load()
            Message.Text = "The current request is from: " & _
               CStr(Request.ServerVariables.Item("REMOTE_ADDRESS"))
         End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>


Request.UrlReferrer

<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeFile="Default.aspx.cs" 
         Inherits="CrossPage1" %>
<!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>CrossPage1</title>
</head>
<body>
    <form id="form1" runat="server" >
    <div>
        Type something here:
        <asp:TextBox runat="server" ID="txt1"></asp:TextBox>
        <asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
                                    runat="server" 
                                    ControlToValidate="txt1"
                                    EnableClientScript="False" 
                                    ErrorMessage="This is a required field.">
        </asp:RequiredFieldValidator><br />
        <br />
        <asp:Button runat="server" 
                    ID="cmdPost" 
                    PostBackUrl="NextPage.aspx" 
                    Text="Cross-Page Postback" />
        <asp:Button runat="server" 
                    ID="cmdTransfer" 
                    Text="Manual Transfer" 
                    OnClick="cmdTransfer_Click" />
    </div>
    </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 CrossPage1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    if (Request.QueryString["err"] != null)
      Page.Validate();
    }
  public TextBox TextBox1
  {
    get { return txt1; }
  }
  protected void cmdTransfer_Click(object sender, EventArgs e)
  {
    Server.Transfer("NextPage.aspx", true);
  }
}

File: NextPage.aspx
<%@ Page Language="C#" 
         AutoEventWireup="true" 
         CodeFile="NextPage.aspx.cs" 
         Inherits="CrossPage2" %>
<!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" >
    <div>
    
    </div>
    </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 CrossPage2 : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    if (PreviousPage != null)
    {
      if (!PreviousPage.IsValid)
      {
        Response.Redirect(Request.UrlReferrer.AbsolutePath + "?err=true");
      }
      else
      {
        Response.Write("You came from a page titled " +
           PreviousPage.Header.Title + "<br /");
        CrossPage1 prevPage = PreviousPage as CrossPage1;
        if (prevPage != null)
        {
          Response.Write("You typed in this: " + prevPage.TextBox1.Text + "<br />");
        }
        if (PreviousPage.IsCrossPagePostBack)
        {
          Response.Write("The page was posted directly");
        }
        else
        {
          Response.Write("You used Server.Transfer()");
        }
      }
    }
  }
}


Showing Parameters via the Params Collection in ASP.NET

<html>
   <head>
      <title>Submit a named parameter via POST</title>
   </head>
<body>
   <form id="form1" action="NextPage.aspx" method="POST">
      <h3>Name:</h3>
      <input type="text" name="name">
      <input type="submit">
   </form>
</body>
</html>
File: NextPage.aspx
<%@ Page Language="vb" %>
<html>
   <head>
      <title>Showing Parameters via the Params Collection in ASP.NET</title>
   </head>
<body>

<%
Dim Counter1, Counter2 As Integer
Dim Keys(), subKeys() As String
Dim ParamColl As NameValueCollection

ParamColl=Request.Params
Keys = ParamColl.AllKeys
For Counter1 = 0 To Keys.GetUpperBound(0)
   Response.Write("Key: " & Keys(Counter1) & "<br>")
   subKeys = ParamColl.GetValues(Counter1) " Get all values under this key.
   For Counter2 = 0 To subKeys.GetUpperBound(0)
      Response.Write("Value " & CStr(Counter2) & ": " & subKeys(Counter2) & "<br>")
   Next Counter2
Next Counter1
%>

</body>
</html>


Showing QueryString values via the QueryString Collection in ASP.NET

<%@ Page Language="vb" %>
<html>
   <head>
      <title>Showing QueryString values via the QueryString Collection in ASP.NET</title>
   </head>
<body>

<%
Dim Counter1, Counter2 As Integer
Dim Keys(), subKeys() As String
Dim queryStringCollection As NameValueCollection

queryStringCollection=Request.QueryString
Keys = queryStringCollection.AllKeys
For Counter1 = 0 To Keys.GetUpperBound(0)
   Response.Write("Key: " & Keys(Counter1) & "<br>")
   subKeys = queryStringCollection.GetValues(Counter1)
   For Counter2 = 0 To subKeys.GetUpperBound(0)
      Response.Write("Value " & CStr(Counter2) & ": " & subKeys(Counter2) & "<br>")
   Next Counter2
Next Counter1
%>
</body>
</html>