public async Task Invoke(HttpContext ctx)
#endif
        {
            try
            {
                await Next?.Invoke(ctx);
            }
            catch (Exception ex)
            {
                _options.Logger.Error("HttpStatusCode set to 500 {0}", ex);
                await _responseMapper.MapAsync(ResponseMessageBuilder.Create(JsonConvert.SerializeObject(ex), 500), ctx.Response);
            }
        }
        public async Task Invoke(HttpContext ctx)
#endif
        {
            try
            {
                await Next?.Invoke(ctx);
            }
            catch (Exception ex)
            {
                Log.Error("HttpStatusCode set to 500", ex);
                await _responseMapper.MapAsync(new ResponseMessage { StatusCode = 500, Body = JsonConvert.SerializeObject(ex) }, ctx.Response);
            }
        }
Esempio n. 3
0
        public async Task Invoke(HttpContext ctx)
#endif
        {
            var request = await _requestMapper.MapAsync(ctx.Request);

            bool               logRequest         = false;
            ResponseMessage    response           = null;
            Mapping            targetMapping      = null;
            RequestMatchResult requestMatchResult = null;

            try
            {
                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
                {
                    // Set start
                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
                    {
                        _options.Scenarios.Add(mapping.Scenario, null);
                    }
                }

                var mappings = _options.Mappings.Values
                               .Select(m => new
                {
                    Mapping     = m,
                    MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _options.Scenarios.ContainsKey(m.Scenario) ? _options.Scenarios[m.Scenario] : null)
                })
                               .ToList();

                if (_options.AllowPartialMapping)
                {
                    var partialMappings = mappings
                                          .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdminInterface)
                                          .OrderBy(m => m.MatchResult)
                                          .ThenBy(m => m.Mapping.Priority)
                                          .ToList();

                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);

                    targetMapping      = bestPartialMatch?.Mapping;
                    requestMatchResult = bestPartialMatch?.MatchResult;
                }
                else
                {
                    var perfectMatch = mappings
                                       .OrderBy(m => m.Mapping.Priority)
                                       .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);

                    targetMapping      = perfectMatch?.Mapping;
                    requestMatchResult = perfectMatch?.MatchResult;
                }

                if (targetMapping == null)
                {
                    logRequest = true;
                    Log.Warn("HttpStatusCode set to 404 : No matching mapping found");
                    response = new ResponseMessage {
                        StatusCode = 404, Body = "No matching mapping found"
                    };
                    return;
                }

                logRequest = !targetMapping.IsAdminInterface;

                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
                {
                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization);
                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
                    {
                        Log.Error("HttpStatusCode set to 401");
                        response = new ResponseMessage {
                            StatusCode = 401
                        };
                        return;
                    }
                }

                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestProcessingDelay.Value);
                }

                response = await targetMapping.ResponseToAsync(request);

                if (targetMapping.Scenario != null)
                {
                    _options.Scenarios[targetMapping.Scenario] = targetMapping.NextState;
                }
            }
            catch (Exception ex)
            {
                Log.Error("HttpStatusCode set to 500", ex);
                response = new ResponseMessage {
                    StatusCode = 500, Body = JsonConvert.SerializeObject(ex)
                };
            }
            finally
            {
                var log = new LogEntry
                {
                    Guid               = Guid.NewGuid(),
                    RequestMessage     = request,
                    ResponseMessage    = response,
                    MappingGuid        = targetMapping?.Guid,
                    MappingTitle       = targetMapping?.Title,
                    RequestMatchResult = requestMatchResult
                };

                LogRequest(log, logRequest);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }
 public async void OwinResponseMapper_MapAsync_Null()
 {
     // Act
     await _sut.MapAsync(null, _responseMock.Object);
 }
        public async Task Invoke(HttpContext ctx)
#endif
        {
            _options.Logger.Debug("New Task Invoke with Request: '{0}'", JsonConvert.SerializeObject(new { Headers = ctx.Request.Headers, Body = "Body not logged here." }));

            var request = await _requestMapper.MapAsync(ctx.Request);

            var logRequestStr = JsonConvert.SerializeObject(request);

            _options.Logger.Debug("Start Finding matching mapping for Request: '{0}'", logRequestStr);

            bool               logRequest         = false;
            ResponseMessage    response           = null;
            Mapping            targetMapping      = null;
            RequestMatchResult requestMatchResult = null;

            System.Collections.Generic.Dictionary <Mapping, RequestMatchResult> log_mappings = new System.Collections.Generic.Dictionary <Mapping, RequestMatchResult>();
            try
            {
                _options.Logger.Debug("Start Scenario mappings for Request: '{0}'", logRequestStr);
                foreach (var mapping in _options.Mappings.Values.Where(m => m?.Scenario != null))
                {
                    // Set start
                    if (!_options.Scenarios.ContainsKey(mapping.Scenario) && mapping.IsStartState)
                    {
                        _options.Scenarios.Add(mapping.Scenario, null);
                    }
                }
                _options.Logger.Debug("Done Getting Scenario mappings for Request: '{0}'", logRequestStr);

                _options.Logger.Debug("Start iterating mapping matchings for Request: '{0}'", logRequestStr);
                var mappings = _options.Mappings.Values
                               .Select(m => new
                {
                    Mapping     = m,
                    MatchResult = m.GetRequestMatchResult(request, m.Scenario != null && _options.Scenarios.ContainsKey(m.Scenario) ? _options.Scenarios[m.Scenario] : null)
                })
                               .ToList();
                _options.Logger.Debug("Done iterating mapping matchings for Request: '{0}'", logRequestStr);

                foreach (var mapping in mappings)
                {
                    if (mapping.MatchResult.LogThis)
                    {
                        log_mappings.Add(mapping.Mapping, mapping.MatchResult);
                    }
                }

                if (_options.AllowPartialMapping)
                {
                    _options.Logger.Debug("Start AllowPartialMapping steps for Request: '{0}'", logRequestStr);
                    var partialMappings = mappings
                                          .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdminInterface)
                                          .OrderBy(m => m.MatchResult)
                                          .ThenBy(m => m.Mapping.Priority)
                                          .ToList();

                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);

                    targetMapping      = bestPartialMatch?.Mapping;
                    requestMatchResult = bestPartialMatch?.MatchResult;
                    _options.Logger.Info("Got PartialMapping steps for Request: '{0}', Mapping: '{1}'", logRequestStr, JsonConvert.SerializeObject(requestMatchResult));
                    _options.Logger.Debug("Done AllowPartialMapping steps for Request: '{0}'", logRequestStr);
                }
                else
                {
                    _options.Logger.Debug("Start Perfect mapping steps for Request: '{0}'", logRequestStr);

                    var perfectMatch = mappings
                                       .OrderBy(m => m.Mapping.Priority)
                                       .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);

                    targetMapping      = perfectMatch?.Mapping;
                    requestMatchResult = perfectMatch?.MatchResult;

                    _options.Logger.Debug("Done Perfect mapping steps for Request: '{0}'", logRequestStr);
                }

                if (targetMapping == null)
                {
                    logRequest = true;
                    _options.Logger.Warn("HttpStatusCode set to 404 : No matching mapping found for request: '{0}'", logRequestStr);
                    response = new ResponseMessage {
                        StatusCode = 404, Body = JsonConvert.SerializeObject(new { Error = "No matching mapping found", RequestMessage = request, LoggedMapFailures = log_mappings })
                    };
                    response.AddHeader("Content-Type", "application/json");
                    return;
                }

                logRequest = !targetMapping.IsAdminInterface;

                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
                {
                    bool present = request.Headers.TryGetValue(HttpKnownHeaderNames.Authorization, out WireMockList <string> authorization);
                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization.ToString()) < MatchScores.Perfect)
                    {
                        _options.Logger.Error("HttpStatusCode set to 401 : For request: '{0}'", logRequestStr);
                        response = new ResponseMessage {
                            StatusCode = 401
                        };
                        return;
                    }
                }

                if (!targetMapping.IsAdminInterface && _options.RequestProcessingDelay > TimeSpan.Zero)
                {
                    await Task.Delay(_options.RequestProcessingDelay.Value);
                }

                response = await targetMapping.ResponseToAsync(request);

                if (targetMapping.Scenario != null)
                {
                    _options.Scenarios[targetMapping.Scenario] = targetMapping.NextState;
                }

                if (targetMapping != null)
                {
                    _options.Logger.Info("Matching mapping found for Request: '{0}', Mapping: '{1}'", logRequestStr, JsonConvert.SerializeObject(targetMapping));
                }

                _options.Logger.Debug("Done Finding matching mapping for Request: '{0}'", logRequestStr);
            }
            catch (Exception ex)
            {
                _options.Logger.Error("Exception thrown: HttpStatusCode set to 500, Exception: '{0}'", ex.ToString());
                response = new ResponseMessage {
                    StatusCode = 500, Body = JsonConvert.SerializeObject(ex)
                };
            }
            finally
            {
                foreach (Mapping mapping in log_mappings.Keys)
                {
                    var faillog = new LogEntry
                    {
                        Timestamp          = DateTime.Now,
                        Guid               = Guid.NewGuid(),
                        RequestMessage     = request,
                        ResponseMessage    = response,
                        MappingGuid        = mapping?.Guid,
                        MappingTitle       = mapping?.Title,
                        RequestMatchResult = log_mappings[mapping]
                    };
                    LogMatch(faillog, true, "");
                }
                var log = new LogEntry
                {
                    Timestamp          = DateTime.Now,
                    Guid               = Guid.NewGuid(),
                    RequestMessage     = request,
                    ResponseMessage    = response,
                    MappingGuid        = targetMapping?.Guid,
                    MappingTitle       = targetMapping?.Title,
                    RequestMatchResult = requestMatchResult
                };

                LogRequest(log, logRequest);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }
Esempio n. 6
0
        public async Task Invoke(HttpContext ctx)
#endif
        {
            if (_options.RequestProcessingDelay > TimeSpan.Zero)
            {
                await Task.Delay(_options.RequestProcessingDelay.Value);

                // Thread.Sleep(_options.RequestProcessingDelay.Value);
            }

            var request = await _requestMapper.MapAsync(ctx.Request);

            ResponseMessage    response           = null;
            Mapping            targetMapping      = null;
            RequestMatchResult requestMatchResult = null;

            try
            {
                var mappings = _options.Mappings
                               .Select(m => new
                {
                    Mapping     = m,
                    MatchResult = m.IsRequestHandled(request)
                })
                               .ToList();

                if (_options.AllowPartialMapping)
                {
                    var partialMappings = mappings
                                          .Where(pm => pm.Mapping.IsAdminInterface && pm.MatchResult.IsPerfectMatch || !pm.Mapping.IsAdminInterface)
                                          .OrderBy(m => m.MatchResult)
                                          .ThenBy(m => m.Mapping.Priority)
                                          .ToList();

                    var bestPartialMatch = partialMappings.FirstOrDefault(pm => pm.MatchResult.AverageTotalScore > 0.0);

                    targetMapping      = bestPartialMatch?.Mapping;
                    requestMatchResult = bestPartialMatch?.MatchResult;
                }
                else
                {
                    var perfectMatch = mappings
                                       .OrderBy(m => m.Mapping.Priority)
                                       .FirstOrDefault(m => m.MatchResult.IsPerfectMatch);

                    targetMapping      = perfectMatch?.Mapping;
                    requestMatchResult = perfectMatch?.MatchResult;
                }

                if (targetMapping == null)
                {
                    response = new ResponseMessage {
                        StatusCode = 404, Body = "No matching mapping found"
                    };
                    return;
                }

                if (targetMapping.IsAdminInterface && _options.AuthorizationMatcher != null)
                {
                    string authorization;
                    bool   present = request.Headers.TryGetValue("Authorization", out authorization);
                    if (!present || _options.AuthorizationMatcher.IsMatch(authorization) < 1.0)
                    {
                        response = new ResponseMessage {
                            StatusCode = 401
                        };
                        return;
                    }
                }

                response = await targetMapping.ResponseToAsync(request);
            }
            catch (Exception ex)
            {
                response = new ResponseMessage {
                    StatusCode = 500, Body = ex.ToString()
                };
            }
            finally
            {
                var log = new LogEntry
                {
                    Guid               = Guid.NewGuid(),
                    RequestMessage     = request,
                    ResponseMessage    = response,
                    MappingGuid        = targetMapping?.Guid,
                    MappingTitle       = targetMapping?.Title,
                    RequestMatchResult = requestMatchResult
                };

                LogRequest(log);

                await _responseMapper.MapAsync(response, ctx.Response);
            }

            await CompletedTask;
        }