public void OnActionExecuting(ActionExecutingContext context)
        {
            string requestId = "";
            var    headers   = context.HttpContext.Request.Headers["RequestId"];

            if (headers.Count > 0)
            {
                requestId = headers[0];
            }

            _diagnosticContext.Set("RequestId", requestId);
            _diagnosticContext.Set("ActionId", context.ActionDescriptor.Id);
            _diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName);
            _diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues);
            _diagnosticContext.Set("ValidationState", context.ModelState.IsValid);
        }
Example #2
0
        public string Get()
        {
            // The request completion event will carry this property
            _diagnosticContext.Set("CatalogLoadTime", 1423);

            return("ok");
        }
Example #3
0
        public IActionResult Get()
        {
            _logger.LogInformation("Hello, world!");

            _diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));

            return(Ok(new { name = "shotigo" }));
        }
        public IActionResult Index()
        {
            _logger.LogInformation("Hello, world!");

            _diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));

            return(View());
        }
Example #5
0
        public static async void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            // Set all the common properties available for every request
            diagnosticContext.Set("Host", request.Host);
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("Scheme", request.Scheme);

            // Set the content-type of the Response at this point
            diagnosticContext.Set("ContentType", httpContext.Response.ContentType);

            // Only set it if available. You're not sending sensitive data in a querystring right?!
            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }



            // Retrieve the IEndpointFeature selected for the request
            var endpoint = httpContext.GetEndpoint();

            if (endpoint is object) // endpoint != null
            {
                diagnosticContext.Set("EndpointName", endpoint.DisplayName);
            }

            diagnosticContext.Set("Request Body", await SerealizarBody(httpContext.Request));
        }
Example #6
0
        public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            diagnosticContext.Set("Host", request.Host);
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("Scheme", request.Scheme);

            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }

            diagnosticContext.Set("ContentType", httpContext.Response.ContentType);

            var endpoint = httpContext.GetEndpoint();

            if (endpoint is not null) // endpoint != null
            {
                diagnosticContext.Set("EndpointName", endpoint.DisplayName);
            }

            var headers = request.Headers;

            if (headers.Any())
            {
                diagnosticContext.Set("Headers", headers);
            }
        }
Example #7
0
        public async Task <IActionResult> PostHook()
        {
            if (Request.Headers.TryGetValue("X-Hub-Delivery", out var delivery))
            {
                _context.Set("GitHubDelivery", delivery[0]);
            }

            if (_cfg.Value.GitHubSecret == null)
            {
                _log.LogError("GitHubSecret not set!");
                return(Unauthorized());
            }

            var ms = new MemoryStream();
            await Request.Body.CopyToAsync(ms);

            ms.Position = 0;

            var sig = Request.Headers["X-Hub-Signature-256"][0];

            if (!sig.StartsWith("sha256="))
            {
                _log.LogTrace("X-Hub-Signature-256 did not start with sha256");
                return(BadRequest());
            }

            var hex = Utility.FromHex(sig.AsSpan("sha256=".Length));

            var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(_cfg.Value.GitHubSecret));

            // ReSharper disable once MethodHasAsyncOverload
            hmac.ComputeHash(ms);
            var ourHash = hmac.Hash !;

            if (!Utility.SecretEqual(hex, ourHash))
            {
                _log.LogInformation("Failed authentication attempt: hash mismatch");
                return(Unauthorized());
            }

            var eventType = Request.Headers["X-GitHub-Event"][0];

            _log.LogInformation("Handling GitHub event of type {Event}", eventType);

            switch (eventType)
            {
            case "push":
                HandlePush(Deserialize <GHPushEvent>(ms));
                break;

            case "pull_request":
                HandlePullRequest(Deserialize <GHPullRequestEvent>(ms));
                break;
            }

            return(Ok());
        }
Example #8
0
        public void TestDiagnosticContext(int id)
        {
            // Dynamically add properties during request processing.
            // TestId will appear in the log created by the app.UseSerilogRequestLogging().
            _diagnosticContext.Set("TestId", id);

            using (LogContext.PushProperty("TestId", id))
                Log.Information("LogContext.PushProperty dynamically add the TestId property this log.");
        }
        public void OnPageHandlerSelected(PageHandlerSelectedContext context)
        {
            var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name;

            if (name != null)
            {
                _diagnosticContext.Set("RazorPageHandler", name);
            }
        }
Example #10
0
        private void EnrichDiagnosticContext(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            // add common
            diagnosticContext.Set("Protocol", httpContext.Request.Protocol);
            diagnosticContext.Set("Scheme", httpContext.Request.Scheme);

            // add user-agent
            if (httpContext.Request.Headers.TryGetValue(HeaderNames.UserAgent, out var userAgent))
            {
                diagnosticContext.Set("UserAgent", userAgent.ToString());
            }

            // add spotify username
            var username = httpContext.User.Claims.GetSpotifyUsername();

            if (!string.IsNullOrWhiteSpace(username))
            {
                diagnosticContext.Set("Username", username);
            }
        }
Example #11
0
    public void OnPageHandlerSelected(PageHandlerSelectedContext context)
    {
        var name = context.HandlerMethod?.Name ?? context.HandlerMethod?.MethodInfo.Name;

        if (name != null)
        {
            _diagnosticContext.Set("RazorPageHandler", name);
        }

        LoggingExtensions.EnrichFromFilterContext(_diagnosticContext, context);
    }
        public IActionResult GetAuthors(
            [FromQuery] AuthorsResourceParameters authorsResourceParameters)
        {
            if (!_propertyMappingService.ValidMappingExistsFor <AuthorDto, Author>(authorsResourceParameters.OrderBy))
            {
                return(BadRequest());
            }

            if (!_propertyCheckerService.TypeHasProperties <AuthorDto>(authorsResourceParameters.Fields))
            {
                return(BadRequest());
            }

            _diagnosticContext.Set("Florian", "True");

            var authorsFromRepo = _courseLibraryRepository.GetAuthors(authorsResourceParameters);

            var paginationMetadata = new
            {
                totalCount  = authorsFromRepo.TotalCount,
                pageSize    = authorsFromRepo.PageSize,
                currentPage = authorsFromRepo.CurrentPage,
                totalPages  = authorsFromRepo.TotalPages
            };

            Response.Headers.Add("X-Pagination",
                                 JsonSerializer.Serialize(paginationMetadata,
                                                          new JsonSerializerOptions {
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            }));

            var links = CreateLinksForAuthors(authorsResourceParameters,
                                              authorsFromRepo.HasPrevious,
                                              authorsFromRepo.HasNext);

            var shapedAuthors = _mapper.Map <IEnumerable <AuthorDto> >(authorsFromRepo)
                                .ShapeData(authorsResourceParameters.Fields);

            var shapedAuthorsWithLinks = shapedAuthors.Select(author =>
            {
                var authorAsDictionary = author as IDictionary <string, object>;
                var authorLinks        = CreateLinksForAuthor((Guid)authorAsDictionary["Id"], null);
                authorAsDictionary.Add("links", authorLinks);
                return(authorAsDictionary);
            });

            var linkedCollectionResource = new
            {
                value = shapedAuthorsWithLinks,
                links
            };

            return(Ok(linkedCollectionResource));
        }
Example #13
0
        public IActionResult Index()
        {
            var logModel = new LogModel();
            var fruit    = new[] { "Apple", "Pear", "Orange" };

            _logger.LogInformation("Hello, world - {fruit} - {@logModel}", fruit, logModel);

            _diagnosticContext.Set("CatalogLoadTime", 123123123123);

            return(View());
        }
Example #14
0
        public async Task InvokeAsync(HttpContext httpContext)
        {
            string requestBody = await GetRequestBody(httpContext.Request).ConfigureAwait(false);

            await _next(httpContext).ConfigureAwait(false);

            if (CheckStatusCodeAndOptions(_options.Mode, httpContext?.Response?.StatusCode))
            {
                _diagnosticContext.Set("RequestBody", requestBody);
            }
        }
Example #15
0
        public static void SetHeaderValue(this IDiagnosticContext diagnosticContext, HttpContext httpContext, string headerName)
        {
            var value = httpContext.GetHeaderValue(headerName);

            if (string.IsNullOrWhiteSpace(value))
            {
                return;
            }

            diagnosticContext.Set(headerName, value);
        }
        public IEnumerable <WeatherForecast> Get()
        {
            _diagnosticContext.Set("CatalogLoadTime", 1423);
            var currentUserId    = int.Parse(User.Identity.Name);
            var _WeatherForecast = new WeatherForecast {
                Date = DateTime.UtcNow, TemperatureC = 35, Summary = "neu", UserId = currentUserId
            };

            _context.WeatherForecasts.Add(_WeatherForecast);
            _context.SaveChanges();
            return(_context.WeatherForecasts);
        }
        public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            // Set all the common properties available for every request
            diagnosticContext.Set(Microsoft.Net.Http.Headers.HeaderNames.Host, request.Host);
            diagnosticContext.Set(Invariants.AspNet.Request.Protocol, request.Protocol);
            diagnosticContext.Set(Invariants.AspNet.Request.Scheme, request.Scheme);

            // Only set it if available. You're not sending sensitive data in a querystring right?!
            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }

            // Set the content-type of the Response at this point
            diagnosticContext.Set(Microsoft.Net.Http.Headers.HeaderNames.ContentType, httpContext.Response.ContentType);

            // Retrieve the IEndpointFeature selected for the request
            var endpoint = httpContext.GetEndpoint();

            if (!ReferenceEquals(endpoint, null))
            {
                diagnosticContext.Set(Invariants.AspNet.Request.EndpointName, endpoint.DisplayName);
            }
        }
        public static void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            // 为每个请求都设置通用的属性
            diagnosticContext.Set("Host", request.Host);
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("Scheme", request.Scheme);
            diagnosticContext.Set("RemoteIpAddress", httpContext.Connection.RemoteIpAddress);
            // 如果要记录 Request Body 或 Response Body
            // 参考 https://stackoverflow.com/questions/60076922/serilog-logging-web-api-methods-adding-context-properties-inside-middleware
            string requestBody = ReadRequestBody(httpContext.Request).Result;

            if (!string.IsNullOrEmpty(requestBody))
            {
                diagnosticContext.Set("RequestBody", requestBody);
            }

            // string responseBody = ReadResponseBody(httpContext.Response).Result;
            // if (!string.IsNullOrEmpty(responseBody))
            // {
            //     diagnosticContext.Set("ResponseBody", requestBody);
            // }

            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }
        }
Example #19
0
        public static async void EnrichFromRequest(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            diagnosticContext.Set("RequestBody", RequestPayload);

            string responseBodyPayload = await ReadResponseBody(httpContext.Response);

            diagnosticContext.Set("ResponseBody", responseBodyPayload);
            ApiResponse responseBody = (ApiResponse)JsonConvert.DeserializeObject(responseBodyPayload, typeof(ApiResponse));

            if (responseBody != null)
            {
                diagnosticContext.Set("ResponseCode", responseBody.Code);
                diagnosticContext.Set("Description", responseBody.Description);
            }

            // Set all the common properties available for every request
            diagnosticContext.Set("Host", request.Host);
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("Scheme", request.Scheme);

            // Only set it if available. You're not sending sensitive data in a querystring right?!
            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }

            // Set the content-type of the Response at this point
            diagnosticContext.Set("ContentType", httpContext.Response.ContentType);

            // Retrieve the IEndpointFeature selected for the request
            var endpoint = httpContext.GetEndpoint();

            if (endpoint is object)             // endpoint != null
            {
                diagnosticContext.Set("EndpointName", endpoint.DisplayName);
            }
        }
Example #20
0
        public async Task OnPageHandlerExecutionAsync(PageHandlerExecutingContext context, PageHandlerExecutionDelegate next)
        {
            var ipAddress = context.HttpContext.Connection.RemoteIpAddress.MapToIPv4();

            var geo = await _geoService.GetCountry(ipAddress.ToString());

            if (geo != null && geo.ip != null)
            {
                _diagnosticContext.Set("Geo", geo, destructureObjects: true);
            }

            await next.Invoke();
        }
        public void Set(string propertyName, object value, bool destructureObjects = false)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
            {
                throw new ArgumentException("Property name is required", nameof(propertyName));
            }

            if (value is null)
            {
                return; // Little value in having nulls in the log
            }
            _diagnosticContext.Set(propertyName, value, destructureObjects);
        }
        private static void EnrichRequest(IDiagnosticContext diagnosticCtx, HttpContext httpCtx)
        {
            diagnosticCtx.Set("IpAddress", httpCtx.Connection?.RemoteIpAddress?.ToString() ?? "- Unknown -");
            diagnosticCtx.Set("User", httpCtx.User?.Identity.Name ?? "- Unauthenticated -");

            if (httpCtx.Request.Path.HasValue)
            {
                diagnosticCtx.Set("Path", httpCtx.Request.Path.Value);
            }

            if (httpCtx.Request.QueryString.HasValue)
            {
                diagnosticCtx.Set("QueryString", httpCtx.Request.QueryString);
            }

            var endpoint = httpCtx.GetEndpoint();

            if (endpoint != null)
            {
                diagnosticCtx.Set("EndpointName", endpoint.DisplayName);
            }
        }
Example #23
0
        public async Task InvokeAsync(HttpContext context, RequestDelegate next)
        {
            var principal     = context.User;
            var principalInfo = _identityService.MapToPrincipalInfo(principal);

            context.SetPrincipalInfo(principalInfo);

            if (principalInfo.UserId != null)
            {
                _diagnosticContext.Set(LoggingConsts.Properties.UserId, principalInfo.UserId);
            }

            await next(context);
        }
Example #24
0
        /// <summary>
        /// Adds WOPI diagnostic codes to the diagnostic context.
        /// </summary>
        /// <param name="diagnosticContext">Serilog's diagnostic context.</param>
        /// <param name="httpContext">HTTP context instance</param>
        public static void EnrichWithWopiDiagnostics(IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            if (diagnosticContext is null)
            {
                throw new System.ArgumentNullException(nameof(diagnosticContext));
            }

            if (httpContext is null)
            {
                throw new System.ArgumentNullException(nameof(httpContext));
            }

            var request = httpContext.Request;

            if (request.Headers.TryGetValue(WopiHeaders.CORRELATION_ID, out var correlationId))
            {
                diagnosticContext.Set(nameof(WopiHeaders.CORRELATION_ID), correlationId.First());
            }

            if (request.Headers.TryGetValue(WopiHeaders.SESSION_ID, out var sessionId))
            {
                diagnosticContext.Set(nameof(WopiHeaders.SESSION_ID), sessionId.First());
            }
        }
Example #25
0
        public async Task InvokeAsync(HttpContext context)
        {
            var originalBodyStream = context.Response.Body;

            using (var responseBody = new MemoryStream())
            {
                context.Response.Body = responseBody;
                await _next(context);

                var responseBodyPayload = await ReadResponseBody(context.Response);

                _diagnosticContext.Set("ResponseBody", responseBodyPayload);
                await responseBody.CopyToAsync(originalBodyStream);
            }
        }
Example #26
0
        public async override Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            if (context.HttpContext.Request.Method.ToUpper() == "POST" || context.HttpContext.Request.Method.ToUpper() == "PUT")
            {
                //var reader = new StreamReader(context.HttpContext.Request.Body);
                //var requestContent = reader.ReadToEndAsync();
                var request = context.HttpContext.Request;
                //Æô¶¯µ¹´ø·½Ê½
                //request.EnableBuffering();
                request.Body.Seek(0, SeekOrigin.Begin);
                using (var reader = new StreamReader(request.Body, Encoding.UTF8))
                {
                    var param = await reader.ReadToEndAsync();

                    _diagnosticContext.Set("Content", param);
                }
                //request.Body.Seek(0, SeekOrigin.Begin);
            }
            _diagnosticContext.Set("RouteData", context.ActionDescriptor.RouteValues);
            _diagnosticContext.Set("ActionName", context.ActionDescriptor.DisplayName);
            _diagnosticContext.Set("ActionId", context.ActionDescriptor.Id);
            _diagnosticContext.Set("ValidationState", context.ModelState.IsValid);
            await base.OnActionExecutionAsync(context, next);
        }
        public IEnumerable <WeatherForecast> Get()
        {
            _logger.LogInformation("Hello, world!");

            _diagnosticContext.Set("IndexCallCount", Interlocked.Increment(ref _callCount));

            var rng = new Random();

            return(Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                Date = DateTime.Now.AddDays(index),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            })
                   .ToArray());
        }
Example #28
0
        public static void EnrichFromRequest(
            IDiagnosticContext diagnosticContext, HttpContext httpContext)
        {
            var request = httpContext.Request;

            diagnosticContext.Set("Host", request.Host);
            diagnosticContext.Set("SourceType", "USER-LOG");
            diagnosticContext.Set("Protocol", request.Protocol);
            diagnosticContext.Set("Scheme", request.Scheme);
            if (request.QueryString.HasValue)
            {
                diagnosticContext.Set("QueryString", request.QueryString.Value);
            }
            diagnosticContext.Set("ContentType", httpContext.Response.ContentType);
            diagnosticContext.Set("User", httpContext.User?.FindFirstValue(Consts.Consts.CLAIM_USERNAME) ?? "None");
            var endpoint = httpContext.GetEndpoint();

            if (endpoint is object)
            {
                string folder = httpContext.Request.Path.Value.Replace(@"/", "_");
                diagnosticContext.Set("LogFolder", folder.ToLower());
                diagnosticContext.Set("EndpointName", httpContext.Request.Path);
            }
        }
Example #29
0
        public async Task Invoke(HttpContext httpContext, ILogger <LogReqResponseMiddleware> logger)
        {
            var request = httpContext.Request;

            request.EnableBuffering();
            // 获取Token信息
            string loginName = httpContext.User.FindFirst(x => x.Type == ClaimTypes.Name)?.Value;
            string addressIP = httpContext.Connection.RemoteIpAddress.ToString();
            //把请求body流转换成字符串
            string bodyAsText = await new StreamReader(request.Body).ReadToEndAsync();//记录请求信息

            _diagnosticContext.Set("PARAMS", $"{request.QueryString} {bodyAsText}");
            var requestStr = $"请求用户名:{loginName} 请求人IP:{addressIP} 协议:{request.Scheme} 主机路径:{request.Host}{request.Path} 参数:{request.QueryString} {bodyAsText}Token:{request.Headers["Authorization"]}";

            logger.LogDebug($"客户端请求【{requestStr}】");
            request.Body.Seek(0, SeekOrigin.Begin);
            var originalBodyStream = httpContext.Response.Body;

            using (var responseBody = new MemoryStream())
            {
                httpContext.Response.Body = responseBody;
                await _next(httpContext);

                var response = httpContext.Response;
                response.Body.Seek(0, SeekOrigin.Begin);
                //转化为字符串
                string text = await new StreamReader(response.Body).ReadToEndAsync();
                //从新设置偏移量0
                response.Body.Seek(0, SeekOrigin.Begin);
                //记录返回值
                var responsestr = $"状态:{response.StatusCode} 内容:{text}";
                logger.LogDebug($"返回【{responsestr}】");
                await responseBody.CopyToAsync(originalBodyStream);
            }
            //return _next(httpContext);
        }
Example #30
0
        public IActionResult Authenticate([FromBody] AuthenticateModel model)
        {
            _diagnosticContext.Set("model", model);
            var user = _userService.Authenticate(model.Username, model.Password);

            if (user == null)
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }

            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Id.ToString()),
                    new Claim(ClaimTypes.Role, model.Username.ToLower() == "admin" ? Policies.Admin : Policies.User),
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token       = tokenHandler.CreateToken(tokenDescriptor);
            var tokenString = tokenHandler.WriteToken(token);


            // return basic user info and authentication token
            return(Ok(new
            {
                Id = user.Id,
                Username = user.Username,
                FirstName = user.FirstName,
                LastName = user.LastName,
                Token = tokenString
            }));
        }