December 13, 2024

SamTech 365

PowerPlatform, Power Apps, Power Automate, PVA, SharePoint, C#, .Net, SQL, Azure News, Tips ….etc

C# .net retrieving web request traces

[vc_row][vc_column][vc_column_text]For most of my applications, especially when I want to write traces or log exceptions, I need to include some details about the request (such as browser, version, language …etc.).

In this method, I am using the HttpContext object to retrieve most of the desired info


[/vc_column_text][vc_column_text]

public static string GetRequestInfos()
        {
            try
            {
                string Details = "<strong>URL : </strong>" + HttpContext.Current.Request.Url;
                Details += Environment.NewLine + "Request Type : </strong>" + HttpContext.Current.Request.RequestType;
                Details += Environment.NewLine + "Content Type : </strong>" + HttpContext.Current.Request.ContentType;
                Details += Environment.NewLine + "<strong>Http Method : </strong>" + HttpContext.Current.Request.HttpMethod + " | <strong>Is Secure : </strong>" + HttpContext.Current.Request.IsSecureConnection;
                Details += Environment.NewLine + "Browser : </strong>" + HttpContext.Current.Request.Browser.Browser;
                Details += Environment.NewLine + "Version : </strong>" + HttpContext.Current.Request.Browser.Version;
                Details += Environment.NewLine + "<strong>User Agent : </strong>" + HttpContext.Current.Request.UserAgent;
                Details += Environment.NewLine + "<strong>Browser Type : </strong>" + HttpContext.Current.Request.Browser.Type + " | <strong>Platform : </strong>" + HttpContext.Current.Request.Browser.Platform;
                Details += Environment.NewLine + "<strong>Mobile : </strong></strong>" + HttpContext.Current.Request.Browser.IsMobileDevice + " | <strong>Mobile model : </strong>" + HttpContext.Current.Request.Browser.MobileDeviceModel;
                Details += Environment.NewLine + "<strong>User Host Address : </strong>" + HttpContext.Current.Request.UserHostAddress;
                if (HttpContext.Current.Request.UserLanguages != null)
                {
                    Details += Environment.NewLine + "User Language : </strong>";
                    foreach (string language in HttpContext.Current.Request.UserLanguages)
                    {
                        Details += language.Split(';')[0] + " | ";
                    }
                }
                return Details;
            }
            catch (Exception exp)
            {
                return exp.Message;
            }
        }

[/vc_column_text][/vc_column][/vc_row]