WebRequestInformation Clase

Definición

Proporciona información sobre la solicitud Web actual.

public ref class WebRequestInformation sealed
public sealed class WebRequestInformation
type WebRequestInformation = class
Public NotInheritable Class WebRequestInformation
Herencia
WebRequestInformation

Ejemplos

En el ejemplo de código siguiente se muestra cómo implementar un evento personalizado que usa el WebRequestInformation tipo .

También se muestra un extracto del archivo de configuración que permite ASP.NET usar este evento personalizado.

Asegúrese de que el evento personalizado se genera en el momento adecuado, es decir, cuando se genere el evento de mantenimiento del sistema equivalente que reemplace.

<healthMonitoring  
  heartBeatInterval="0" enabled="true">  

  <profiles>  
    <add name="Custom"   
      minInstances="1"   
      maxLimit="Infinite"   
      minInterval="00:00:00" />  
  </profiles>  

  <eventMappings>  

    <add   
      name="SampleWebRequestInformation"   
      type="SamplesAspNet.SampleWebRequestInformation,webrequestinformation,Version=1.0.1782.28745, Culture=neutral, PublicKeyToken=79955d9b8521c250,processorArchitecture=MSIL" />  

  </eventMappings>  

  <rules>  

    <add name="Custom Web Request Info Event"   
      eventName="SampleWebRequestInformation"   
      provider="EventLogProvider"  
      profile="Custom" />  

  </rules>  

</healthMonitoring>  

using System;
using System.Text;
using System.Web;
using System.Web.Management;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace SamplesAspNet
{
    // Implements a custom WebRequestEvent that uses
    // WebRequestInformation. 
    public class SampleWebRequestInformation :
        WebRequestEvent
    {
        private StringBuilder eventInfo;

        // Instantiate events identified 
        // only by their event code.
        public SampleWebRequestInformation(string msg,
            object eventSource, int eventCode):
        base(msg, eventSource, eventCode)
        {
            // Perform custom initialization.
            eventInfo = new StringBuilder();
            eventInfo.Append(string.Format(
                "Event created at: {0}",
                EventTime.ToString()));
        }

        // Instantiate events identified by 
        // their event code.and related 
        // event detailed code.
        public SampleWebRequestInformation(string msg,
            object eventSource, int eventCode,
            int eventDetailCode)
            :
            base(msg, eventSource,
            eventCode, eventDetailCode)
        {
            // Perform custom initialization.
            eventInfo = new StringBuilder();
            eventInfo.Append(string.Format(
                "Event created at: {0}",
                EventTime.ToString()));
        }


        // Raises the event.
        public override void Raise()
        {
            // Perform custom processing. 
            eventInfo.Append(string.Format(
                "Event raised at: {0}",
               EventTime.ToString()));
            // Raise the event.
            base.Raise();
        }

        // Get the request path.
        public string GetRequestPath()
        {
            // Get the request path.
            return (string.Format(
                "Request path: {0}",
                RequestInformation.RequestPath));
        }

        // Get the request URL.
        public string GetRequestUrl()
        {
            // Get the request URL.
            return (string.Format(
                "Request URL: {0}",
                RequestInformation.RequestUrl));
        }

        // Get the request user host address.
        public string GetRequestUserHostAdddress()
        {
            // Get the request user host address.
            return (string.Format(
                "Request user host address: {0}",
                RequestInformation.UserHostAddress));
        }

        // Get the request principal.
        public string GetRequestPrincipal()
        {
            // Get the request principal.
            return (string.Format(
                "Request principal name: {0}",
                RequestInformation.Principal.Identity.Name));
        }


        // Formats Web request event information.
        public override void FormatCustomEventDetails(
         WebEventFormatter formatter)
        {

            // Add custom data.

            formatter.AppendLine("");
            formatter.AppendLine(
                "Custom Request Information:");

            formatter.IndentationLevel += 1;

            // Display the request information obtained 
            // using the WebRequestInformation object.
            formatter.AppendLine(GetRequestPath());
            formatter.AppendLine(GetRequestUrl());
            formatter.AppendLine(GetRequestUserHostAdddress());
            formatter.AppendLine(GetRequestPrincipal());

            formatter.IndentationLevel -= 1;

            formatter.AppendLine(eventInfo.ToString());
        }

    }
}
Imports System.Text
Imports System.Web
Imports System.Web.Management
Imports System.Web.UI
Imports System.Web.UI.WebControls


' Implements a custom WebRequestEvent that uses
' WebRequestInformation. 

Public Class SampleWebRequestInformation
   Inherits WebRequestEvent
   Private eventInfo As StringBuilder
   
   
   ' Instantiate events identified 
   ' only by their event code.
    Public Sub New(ByVal msg As String, _
    ByVal eventSource As Object, _
    ByVal eventCode As Integer)
        MyBase.New(msg, eventSource, eventCode)
        ' Perform custom initialization.
        eventInfo = New StringBuilder()
        eventInfo.Append(String.Format( _
        "Event created at: {0}", EventTime.ToString()))
    End Sub
   
   
   ' Instantiate events identified by 
   ' their event code.and related 
   ' event detailed code.
    Public Sub New(ByVal msg As String, _
    ByVal eventSource As Object, _
    ByVal eventCode As Integer, _
    ByVal eventDetailCode As Integer)
        MyBase.New(msg, eventSource, _
        eventCode, eventDetailCode)
        ' Perform custom initialization.
        eventInfo = New StringBuilder()
        eventInfo.Append(String.Format( _
        "Event created at: {0}", EventTime.ToString()))
    End Sub
   
   
   ' Raises the event.
   Public Overrides Sub Raise()
      ' Perform custom processing. 
        eventInfo.Append(String.Format( _
        "Event raised at: {0}", EventTime.ToString()))
      ' Raise the event.
      MyBase.Raise()
   End Sub
   
   ' Get the request path.
   Public Function GetRequestPath() As String
      ' Get the request path.
        Return String.Format( _
        "Request path: {0}", RequestInformation.RequestPath)
   End Function 'GetRequestPath
   
   ' Get the request URL.
   Public Function GetRequestUrl() As String
      ' Get the request URL.
        Return String.Format("Request URL: {0}", _
        RequestInformation.RequestUrl)
   End Function 'GetRequestUrl
   
   ' Get the request user host address.
   Public Function GetRequestUserHostAdddress() As String
      ' Get the request user host address.
        Return String.Format( _
        "Request user host address: {0}", _
        RequestInformation.UserHostAddress)
   End Function 'GetRequestUserHostAdddress
   
   ' Get the request principal.
   Public Function GetRequestPrincipal() As String
      ' Get the request principal.
        Return String.Format( _
        "Request principal name: {0}", _
        RequestInformation.Principal.Identity.Name)
   End Function 'GetRequestPrincipal
   
   ' Formats Web request event information.
    Public Overrides Sub FormatCustomEventDetails( _
    ByVal formatter As WebEventFormatter)

        ' Add custom data.
        formatter.AppendLine("")
        formatter.AppendLine("Custom Request Information:")

        formatter.IndentationLevel += 1

        ' Display the request information obtained 
        ' using the WebRequestInformation object.
        formatter.AppendLine(GetRequestPath())
        formatter.AppendLine(GetRequestUrl())
        formatter.AppendLine(GetRequestUserHostAdddress())
        formatter.AppendLine(GetRequestPrincipal())
        formatter.IndentationLevel -= 1

        formatter.AppendLine(eventInfo.ToString())
    End Sub

End Class

Comentarios

ASP.NET supervisión de estado permite al personal de producción y operaciones administrar las aplicaciones web implementadas. El System.Web.Management espacio de nombres contiene los tipos de eventos de mantenimiento responsables de empaquetar los datos de estado de mantenimiento de la aplicación y los tipos de proveedor responsables de procesar estos datos. También contiene tipos auxiliares que ayudan durante la administración de eventos de mantenimiento.

Las instancias de la WebRequestInformation clase contienen información que se obtiene mediante los WebRequestEventtipos , WebAuditEvent, WebErrorEvento WebRequestErrorEvent .

La aplicación necesita los permisos adecuados para acceder a la información protegida proporcionada por este tipo.

Nota

En la mayoría de los casos, podrá usar los tipos de supervisión de estado ASP.NET tal como se implementa y controlará el sistema de supervisión de estado especificando valores en la healthMonitoring sección de configuración. También puede derivar de los tipos de supervisión de estado para crear sus propios eventos y proveedores personalizados. Para obtener un ejemplo de creación de una clase de eventos personalizada, consulte el ejemplo proporcionado en este tema.

Propiedades

Principal

Obtiene la instancia de la entidad de seguridad del código administrado que está asociado a la solicitud Web.

RequestPath

Obtiene la ruta de acceso física de la solicitud Web.

RequestUrl

Obtiene la ruta de acceso lógica de la solicitud.

ThreadAccountName

Obtiene una cadena que representa el nombre de inicio de sesión de Windows del usuario en cuyo nombre se está ejecutando el código.

UserHostAddress

Obtiene la dirección del host del usuario.

Métodos

Equals(Object)

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
FormatToString(WebEventFormatter)

Da formato a la información de solicitud Web.

GetHashCode()

Sirve como la función hash predeterminada.

(Heredado de Object)
GetType()

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()

Crea una copia superficial del Object actual.

(Heredado de Object)
ToString()

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a

Consulte también