C# .NET - Context.Request.ServerVariables in a webservice in c#

Asked By sunny C on 06-Nov-08 06:15 AM

Hi all,

Can you please let me know what are all server variables that we can get from Context.Request.ServerVariables.

My requirement is to catch the field values like

Client IP, User Name, Server Name, Server IP, Method (eg; get or post), URI Stem (eg: an HTML page, a CGI program, or a script), URI Query, Bytes Sent, Bytes Received, Time Taken (The length of time the action took.), Referer ....

Actually, these are the fields which IIS logs into log file. I can get these values by reading that log file into Excel sheet but i cannot map it to the userid who is accessing my application.

So if I can get these values from Context.Request.ServerVariables then i can map them to the user who is using my application.

Any suggestions please?

Thanks in advance,

Sunny

Context.Request.ServerVariables in a webservice in c#

sunny C replied to sunny C on 06-Nov-08 06:37 AM

Hi All,

I got most of these values from the below code. But i couldn't get the some other fields like (

Bytes Sent: The number of bytes sent by the server,

Bytes Received:  The number of bytes received by the server.,

Time Taken:  The length of time the action took

).

Can you let me know how can i get them from server variables?

NameValueCollection NVCSrvElements = Context.Request.ServerVariables;

for (int item=0; item<NVCSrvElements.Keys.Count; item++)

{

Response.Write(NVCSrvElements.Keys[item] + " -- " + NVCSrvElements[item] + "<br>") ;

}

yes

Web Star replied to sunny C on 06-Nov-08 06:42 AM

u can use Context.Request.ServerVariables  in web services

<%@ WebService Language="c#" class="AuthVarsService" %>
using System;
using System.Web;
using System.Web.Services;
using System.Security.Principal;

public class AuthVarsService : WebService {

    [WebMethod]
    public String GetValue()
   {
String _MyString="";

WindowsImpersonationContext ctx = ((WindowsIdentity)Context.User.Identity).Impersonate();

_MyString  += "{Request.IsAuthenticated = " + Context.Request.IsAuthenticated + "}<br>";
_MyString  += "{AUTH_TYPE = " + Context.Request.ServerVariables["AUTH_TYPE"]  + "}<br>";
_MyString  += "{AUTH_USER = " + Context.Request.ServerVariables["AUTH_USER"]  + "}<br>";
_MyString  += "{AUTH_PASSWORD = " + Context.Request.ServerVariables["AUTH_PASSWORD"]  + "}<br>";
_MyString  += "{LOGON_USER = " + Context.Request.ServerVariables["LOGON_USER"]  + "}<br>";
_MyString  += "{REMOTE_USER = " + Context.Request.ServerVariables["REMOTE_USER"]  + "}<br>";
_MyString += "{Context.User.Identity.Name =" + Context.User.Identity.Name + "}<br>";
_MyString += "{Context.User.Identity.AuthenticationType =" + Context.User.Identity.AuthenticationType  + "}<br>";

_MyString += "{WindowsIdentity.GetCurrent().Name =" + System.Security.Principal.WindowsIdentity.GetCurrent().Name + "}" ;

return _MyString;
   }

}
 

Context.Request.ServerVariables in a webservice in c#

Asked By sunny C on 06-Nov-08 07:11 AM

Thanks for the reply Arvind and Lalji.

Can you suggest me any way that i can get the below field values from the server variables?

Bytes Sent: The number of bytes sent by the server,

Bytes Received:  The number of bytes received by the server.,

Time Taken:  The length of time the action took

Thanks In advance,

Sunny

try this code
C_A P replied to sunny C on 06-Nov-08 11:14 AM

HttpRequest Object Members,

UserHostAddress Gets the IP host address of the remote client.
UserHostName Gets the DNS name of the remote client.

And UserLanguages,

ASP. Net’s Request object has a UserLanguages collection that allows you to read the browser’s currently active language.

HttpRequest Request = HttpContext.Current.Request;
string Lang =  Request.UserLanguages[0];
Response.Write(Lang.ToString());

For ex., if the country is gb(great britain) then the response.write shows en-gb ( english-great britain) and with this I think you will be able to find the Country.

For more info, pls refer to the below links,
http://west-wind.com/weblog/posts/334.aspx

Reply
Binny ch replied to sunny C on 06-Nov-08 11:18 AM
Private iWin32StatusCode As Integer = Nothing ' (sc-win32-status)

Private iBytesSentByServer As Long = 0 ' (sc-bytes)

Private iBytesReceivedByServer As Long = 0 ' (cs-bytes)

Private iProcessingTime As Long = 0 ' (time-taken)

Private sRequestProtocol As String = "" ' (cs-version)

Private sHostHeader As String = "" ' (cs-host)

Private sUserAgent As String = "" ' (cs(User-Agent))

Private sCookie As String = "" ' (cs(Cookie))

Private sReferer As String = "" ' (cs(Referer))

' Additional Useful Fields

Private sServerSoftware As String = ""

Private sW3CExtendedLogFormatVersion As String = ""

Private dStartProcessDateTime As DateTime

Private dEndProcessDateTime As DateTime 

Private sBrowserMinorVersion As String = ""

Private sRequestContentType As String = ""

Private sResponseContentType As String = ""

Private sCrawler As String = ""

' dsn is in machine.config files

Private dsn As String = CType(ConfigurationSettings.AppSettings("WebLoggerDSN"), String)

Private conn As SqlConnection

Private cmd As SqlCommand

Public Sub Init(ByVal app As HttpApplication) Implements IHttpModule.Init

AddHandler app.BeginRequest, AddressOf BeginRequest

AddHandler app.EndRequest, AddressOf EndRequest

AddHandler app.Error, AddressOf OnError

End Sub

Public Sub Dispose() Implements IHttpModule.Dispose

' add clean-up code here if required

dsn =

Nothing

cmd =

Nothing

conn.Close()

conn =

Nothing

End Sub

Public Sub BeginRequest(ByVal sender As Object, ByVal e As EventArgs)

dStartProcessDateTime = DateTime.Now

' Get access to the request context

Dim context As HttpApplication

context =

CType(sender, HttpApplication)

' Create stream watcher so we can get bytes downloaded

Dim app As HttpApplication = DirectCast(sender, HttpApplication)

streamWatcher =

New WebLogger.TransparentStream(app.Response.Filter)

app.Response.Filter = streamWatcher

.sStartRequestDate = dStartProcessDateTime.ToString("yyyy-MM-dd")

' Time (time) - The time that the activity occurred.

sStartRequestTime = dStartProcessDateTime.ToString("HH:mm:ss")

' Client IP (c-ip) - The IP address of the client that accessed your server.

sClientIP = context.Request.ServerVariables("HTTP_X_FORWARDED_FOR")

If sClientIP = "" Or sClientIP = Nothing Then

sClientIP = context.Request.ServerVariables("REMOTE_ADDR")

End If

' User Name (cs-username) - The name of the authenticated user who accessed your server.

' This does not include anonymous users, who are represented by a hyphen (-).

sAuthUserName = context.Request.ServerVariables("AUTH_USER")

' Service Name (s-sitename) - The Internet service and instance number that was accessed by a client.

sServiceName = context.Request.ServerVariables("INSTANCE_META_PATH")

' Server Name (s-computername) - The name of the server on which the log entry was generated.

'sServerName = context.Request.ServerVariables("SERVER_NAME")

Try

sServerName = Dns.GetHostName()

Catch

sServerName =

Nothing

End Try

' Server IP Address (s-ip) - The IP address of the server on which the log entry was generated.

sServerIP = context.Request.ServerVariables("LOCAL_ADDR")

' Server Port (s-port) - The port number the client is connected to.

iServerPort = context.Request.ServerVariables("SERVER_PORT")

' Method (cs-method) - The action the client was trying to perform (for example, a GET method).

sHTTPMethod = context.Request.ServerVariables("REQUEST_METHOD")

' URI Stem (cs-uri-stem) - The resource accessed; for example, Default.htm.

sURLVisited = context.Request.ServerVariables("URL")

' URI Query (cs-uri-query) - The query, if any, the client was trying to perform.

sQueryString = context.Request.ServerVariables("QUERY_STRING")

' Protocol Status (sc-status) - The status of the action, in HTTP or FTP terms.

iProtocolStatusCode = context.Response.StatusCode

' Win32® Status (sc-win32-status) - The status of the action, in terms used by Microsoft Windows®.

iWin32StatusCode =

Nothing

' Bytes Sent (sc-bytes) - The number of bytes sent by the server.

' [This value is retrieved in EndRequest]

iBytesSentByServer = 0

' Bytes Received (cs-bytes) - The number of bytes received by the server.

iBytesReceivedByServer = context.Request.ServerVariables("CONTENT_LENGTH")

' Time Taken (time-taken) - The duration of time, in milliseconds, that the action consumed.

' [This value is retrieved in EndRequest]

iProcessingTime = 0

' Protocol Version (cs-version) - The protocol (HTTP, FTP) version used by the client. For

' HTTP this will be either HTTP 1.0 or HTTP 1.1.

sRequestProtocol = context.Request.ServerVariables("SERVER_PROTOCOL")

' Host (cs-host) - Displays the content of the host header.

sHostHeader = context.Request.Headers("Host")

' User Agent (cs(User-Agent)) - The browser used on the client.

sUserAgent = context.Request.ServerVariables("HTTP_USER_AGENT")

' Cookie (cs(Cookie)) - The content of the cookie sent or received, if any.

sCookie = context.Request.Headers("Cookie")

' Referrer (cs(Referer)) - The previous site visited by the user. This site provided a link to

' the current site.

sReferer = context.Request.ServerVariables("HTTP_REFERER")

 

Go through this link its will help u know more details:

http://forums.asp.net/t/1057552.aspx