public void Publish <TEvent>([NotNull] TEvent @event) where TEvent : EventBase { var route = _routeResolver.Resolve <TEvent>(); var message = JsonConvert.SerializeObject(@event); var body = Encoding.UTF8.GetBytes(message); _consumerChannel.BasicPublish(ExchangeName, route, true, null, body); }
public void Should_set_status_code_to_500_if_route_throws() { var errorRoute = new Route("GET", "/", null, x => { throw new NotImplementedException(); }); A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored, A <IRouteCache> .Ignored)).Returns(new ResolveResult(errorRoute, DynamicDictionary.Empty, null, null)); var request = new Request("GET", "/", "http"); var result = this.engine.HandleRequest(request); result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.errorHandler = A.Fake<IErrorHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._)).Invokes(x => this.context.Response = new Response()); A.CallTo(() => errorHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null, null)); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg => { return (Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1]); }); this.engine = new NancyEngine(this.requestDispatcher, contextFactory, new[] { this.errorHandler }, A.Fake<IRequestTracing>()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
/// <summary> /// Invokes pre-requirements such as authentication and stuff for the supplied context /// reference: https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Routing/DefaultRequestDispatcher.cs /// </summary> /// <param name="context"></param> /// <returns></returns> private static Response InvokePreRequirements(NancyContext context) { var resolution = _routeResolver.Resolve(context); var preRequirements = resolution.Before; return(preRequirements.Invoke(context)); }
public NancyEngineFixture() { this.resolver = A.Fake <IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.errorHandler = A.Fake <IErrorHandler>(); this.requestDispatcher = A.Fake <IRequestDispatcher>(); A.CallTo(() => this.requestDispatcher.Dispatch(A <NancyContext> ._)).Invokes(x => this.context.Response = new Response()); A.CallTo(() => errorHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false); contextFactory = A.Fake <INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null, null)); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake <IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A <Route> ._, A <DynamicDictionary> ._, A <NancyContext> ._)).ReturnsLazily(arg => { return((Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1])); }); this.engine = new NancyEngine(this.requestDispatcher, contextFactory, new[] { this.errorHandler }, A.Fake <IRequestTracing>()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public void Initialize(IPipelines pipelines) { pipelines.BeforeRequest.AddItemToStartOfPipeline( context => { var route = routeResolver.Resolve(context); if (route == null || route.Route == null || route.Route.Description == null) // probably not necessary but don't want the chance of losing visibility on anything { NewRelicAgent.SetTransactionName( context.Request.Method, context.Request.Url.ToString()); } else { NewRelicAgent.SetTransactionName( route.Route.Description.Method, route.Route.Description.Path); } return(null); }); pipelines.OnError.AddItemToEndOfPipeline( (context, ex) => { NewRelicAgent.NoticeError( ex); return(null); }); }
private string GetRequestPathTemplate(NancyContext context) { var resolveResult = RouteResolver.Resolve(context); return(resolveResult.After == null ? UNKNOWN_REQUEST_PATH : $"{context.Request.Method} {resolveResult.Route.Description.Path}"); }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake<IStatusCodeHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); this.diagnosticsConfiguration = new DiagnosticsConfiguration(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)).Invokes((x) => this.context.Response = new Response()); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg => { return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result; }); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.route = new FakeRoute(); A.CallTo(() => resolver.Resolve(A<Request>.Ignored, A<IRouteCache>.Ignored.Argument)).Returns(route); this.engine = new NancyEngine(resolver, A.Fake<IRouteCache>()); }
/// <summary> /// Invokes pre-requirements such as authentication and stuff for the supplied context /// reference: https://github.com/NancyFx/Nancy/blob/master/src/Nancy/Routing/DefaultRequestDispatcher.cs /// </summary> /// <param name="context"></param> /// <returns></returns> private static Response InvokePreRequirements(NancyContext context) { var resolution = _routeResolver.Resolve(context); var preRequirements = resolution.Before; var task = preRequirements.Invoke(context, new CancellationToken(false)); task.Wait(); return(context.Response); }
public RequestModel(NancyContext context, IRootPathProvider rootPathProvider, IRouteResolver routeResolver) { this.context = context; this.rootPathProvider = rootPathProvider; this.routeResolution = routeResolver.Resolve(context); Cookies = this.context.Request.Headers.Cookie.Select(x => new CookieModel(x)).ToArray(); QueryString = ((DynamicDictionary)this.context.Request.Query).Serialize(); Parameters = this.routeResolution.Parameters.Serialize(); }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); ctx.Request.Url.BasePath = string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path); ctx.Request.Url.Path = ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length); if (ctx.Request.Url.Path.Length.Equals(0)) { ctx.Request.Url.Path = "/"; } if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(diagnosticsConfiguration.CookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return(view); } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Item2; var resolveResultPreReq = resolveResult.Item3; var resolveResultPostReq = resolveResult.Item4; ExecuteRoutePreReq(ctx, resolveResultPreReq); if (ctx.Response == null) { ctx.Response = resolveResult.Item1.Invoke(resolveResult.Item2); } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResultPostReq != null) { resolveResultPostReq.Invoke(ctx); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return(ctx.Response); }
public MvcAction BuildAction(RequestContext requestContext) { var actionContext = _actionResolver.Resolve(requestContext); var controllerInstance = (Controller)_controllerActivator.Create(actionContext); var controllerContext = new ControllerContext(controllerInstance); controllerInstance.Request = requestContext; return(new MvcAction(actionContext, controllerContext)); }
private async Task HandleContextAsync(HttpListenerContext listenerContext) { // TODO: implement request handling try { var result = _routeResolver.Resolve(listenerContext.Request); listenerContext.Response.StatusCode = (int)HttpStatusCode.OK; using (var writer = new BinaryWriter(listenerContext.Response.OutputStream)) writer.Write(result); } catch (Exception ex) { } }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored, A<IRouteCache>.Ignored.Argument)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null)); this.engine = new NancyEngine(resolver, A.Fake<IRouteCache>(), contextFactory); }
public NancyEngineFixture() { this.resolver = A.Fake <IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); contextFactory = A.Fake <INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored, A <IRouteCache> .Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null)); this.engine = new NancyEngine(resolver, A.Fake <IRouteCache>(), contextFactory); }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(DiagsCookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return(view); } // TODO - duplicate the context and strip out the "_/Nancy" bit so we don't need to use it in the module var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Item2; var resolveResultPreReq = resolveResult.Item3; var resolveResultPostReq = resolveResult.Item4; ExecuteRoutePreReq(ctx, resolveResultPreReq); if (ctx.Response == null) { ctx.Response = resolveResult.Item1.Invoke(resolveResult.Item2); } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResultPostReq != null) { resolveResultPostReq.Invoke(ctx); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); // If we duplicate the context this makes more sense :) return(ctx.Response); }
public NancyEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.Tracing( enabled: true, displayErrorTraces: true); this.resolver = A.Fake <IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake <IStatusCodeHandler>(); this.requestDispatcher = A.Fake <IRequestDispatcher>(); this.negotiator = A.Fake <IResponseNegotiator>(); A.CallTo(() => this.requestDispatcher.Dispatch(A <NancyContext> ._, A <CancellationToken> ._)) .Returns(Task.FromResult(new Response())); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false); contextFactory = A.Fake <INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A <Request> ._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake <IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A <Route> ._, A <CancellationToken> ._, A <DynamicDictionary> ._, A <NancyContext> ._)).ReturnsLazily(arg => { return(((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A <CancellationToken> ._).Result); }); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake <IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.errorHandler = A.Fake<IErrorHandler>(); A.CallTo(() => errorHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored, A<IRouteCache>.Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null)); this.engine = new NancyEngine(resolver, A.Fake<IRouteCache>(), contextFactory, this.errorHandler); }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(diagnosticsConfiguration.CookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return(view); } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { // Don't care about async here, so just get the result var task = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); task.Wait(); ctx.Response = task.Result; } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return(ctx.Response); }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx, environment); view.WithCookie( new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return(view); } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { var routeResult = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); routeResult.Wait(); ctx.Response = (Response)routeResult.Result; } if (ctx.Request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return(ctx.Response); }
public NancyEngineFixture() { this.resolver = A.Fake <IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake <IStatusCodeHandler>(); this.requestDispatcher = A.Fake <IRequestDispatcher>(); this.diagnosticsConfiguration = new DiagnosticsConfiguration(); A.CallTo(() => this.requestDispatcher.Dispatch(A <NancyContext> ._)).Invokes(x => this.context.Response = new Response()); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false); contextFactory = A.Fake <INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A <Request> ._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake <IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A <Route> ._, A <DynamicDictionary> ._, A <NancyContext> ._)).ReturnsLazily(arg => { return((Response)((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1])); }); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake <IRequestTracing>(), this.diagnosticsConfiguration, new DisabledStaticContentProvider()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public void Should_set_status_code_to_500_if_route_throws() { // Given var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null); A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context)).Throws(new NotImplementedException()); var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); // Then result.Response.StatusCode.ShouldEqual(HttpStatusCode.InternalServerError); }
public NancyEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.Tracing( enabled: true, displayErrorTraces: true); this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake<IStatusCodeHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); this.negotiator = A.Fake<IResponseNegotiator>(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)) .Returns(Task.FromResult(new Response())); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public NancyEngineFixture() { this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.errorHandler = A.Fake<IErrorHandler>(); A.CallTo(() => errorHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null)); var applicationPipelines = new Pipelines(); this.engine = new NancyEngine(resolver, contextFactory, new[] { this.errorHandler }, A.Fake<IRequestTracing>()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public NancyEngineFixture() { this.resolver = A.Fake <IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.errorHandler = A.Fake <IErrorHandler>(); A.CallTo(() => errorHandler.HandlesStatusCode(A <HttpStatusCode> .Ignored, A <NancyContext> .Ignored)).Returns(false); contextFactory = A.Fake <INancyContextFactory>(); A.CallTo(() => contextFactory.Create()).Returns(context); A.CallTo(() => resolver.Resolve(A <NancyContext> .Ignored)).Returns(new ResolveResult(route, DynamicDictionary.Empty, null, null)); var applicationPipelines = new Pipelines(); this.engine = new NancyEngine(resolver, contextFactory, new[] { this.errorHandler }, A.Fake <IRequestTracing>()) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public async Task RouteAsync(RouteContext context) { // Abort and proceed to other routes in the route table if path contains api or ui string[] segments = context.HttpContext.Request.Path.Value.Split(new[] { '/' }); if (segments.Any(segment => segment.Equals("api", StringComparison.OrdinalIgnoreCase) || segment.Equals("brics", StringComparison.OrdinalIgnoreCase))) { return; } var requestCulture = DetectRequestCulture(context.HttpContext); IResolveResult result = await _routeResolver.Resolve(context, requestCulture); if (result != null) { context.RouteData.Values[ControllerKey] = result.Controller; context.RouteData.Values[ActionKey] = result.Action; context.HttpContext.Items[CurrentNodeKey] = result.TrieNode; } await _next.RouteAsync(context); }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(diagnosticsConfiguration.CookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { // Don't care about async here, so just get the result var task = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); task.Wait(); ctx.Response = task.Result; } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return ctx.Response; }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(DiagsCookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } // TODO - duplicate the context and strip out the "_/Nancy" bit so we don't need to use it in the module var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Item2; var resolveResultPreReq = resolveResult.Item3; var resolveResultPostReq = resolveResult.Item4; ExecuteRoutePreReq(ctx, resolveResultPreReq); if (ctx.Response == null) { ctx.Response = resolveResult.Item1.Invoke(resolveResult.Item2); } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResultPostReq != null) { resolveResultPostReq.Invoke(ctx); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); // If we duplicate the context this makes more sense :) return ctx.Response; }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer, INancyEnvironment environment) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); if (session == null) { var view = GetDiagnosticsLoginView(ctx, environment); view.WithCookie( new NancyCookie(diagnosticsConfiguration.CookieName, string.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Parameters; ExecuteRoutePreReq(ctx, CancellationToken, resolveResult.Before); if (ctx.Response == null) { var routeResult = resolveResult.Route.Invoke(resolveResult.Parameters, CancellationToken); routeResult.Wait(); ctx.Response = (Response)routeResult.Result; } if (ctx.Request.Method.Equals("HEAD", StringComparison.OrdinalIgnoreCase)) { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResult.After != null) { resolveResult.After.Invoke(ctx, CancellationToken); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return ctx.Response; }
private static Response ExecuteDiagnostics(NancyContext ctx, IRouteResolver routeResolver, DiagnosticsConfiguration diagnosticsConfiguration, DefaultObjectSerializer serializer) { var session = GetSession(ctx, diagnosticsConfiguration, serializer); ctx.Request.Url.BasePath = string.Concat(ctx.Request.Url.BasePath, diagnosticsConfiguration.Path); ctx.Request.Url.Path = ctx.Request.Url.Path.Substring(diagnosticsConfiguration.Path.Length); if (ctx.Request.Url.Path.Length.Equals(0)) { ctx.Request.Url.Path = "/"; } if (session == null) { var view = GetDiagnosticsLoginView(ctx); view.AddCookie( new NancyCookie(diagnosticsConfiguration.CookieName, String.Empty, true) { Expires = DateTime.Now.AddDays(-1) }); return view; } var resolveResult = routeResolver.Resolve(ctx); ctx.Parameters = resolveResult.Item2; var resolveResultPreReq = resolveResult.Item3; var resolveResultPostReq = resolveResult.Item4; ExecuteRoutePreReq(ctx, resolveResultPreReq); if (ctx.Response == null) { ctx.Response = resolveResult.Item1.Invoke(resolveResult.Item2); } if (ctx.Request.Method.ToUpperInvariant() == "HEAD") { ctx.Response = new HeadResponse(ctx.Response); } if (resolveResultPostReq != null) { resolveResultPostReq.Invoke(ctx); } AddUpdateSessionCookie(session, ctx, diagnosticsConfiguration, serializer); return ctx.Response; }
/// <inheritdoc /> public async Task Execute(MazeContext context, IChannelServer channelServer) { _logger.LogDebug($"Resolve Maze path {context.Request.Path}"); var result = _routeResolver.Resolve(context); if (!result.Success) { _logger.LogDebug("Path not found"); await WriteError(context, BusinessErrors.Commander.RouteNotFound(context.Request.Path), StatusCodes.Status404NotFound); return; } _logger.LogDebug( $"Route resolved (package: {result.RouteDescription.PackageIdentity}). Get cached route info."); var route = _routeCache.Routes[result.RouteDescription]; var actionContext = new DefaultActionContext(context, route, result.Parameters.ToImmutableDictionary()); _logger.LogDebug($"Invoke method {route.RouteMethod}"); IActionResult actionResult; try { switch (route.RouteType) { case RouteType.Http: actionResult = await route.ActionInvoker.Value.Invoke(actionContext); break; case RouteType.ChannelInit: _logger.LogDebug("Create channel {channelName}", actionContext.Route.ControllerType.FullName); var channel = await route.ActionInvoker.Value.InitializeChannel(actionContext, channelServer); context.Response.Headers.Add(HeaderNames.Location, "ws://channels/" + channel.ChannelId); actionResult = new StatusCodeResult(StatusCodes.Status201Created); break; case RouteType.Channel: var channelId = int.Parse(actionContext.Context.Request.Headers["ChannelId"]); _logger.LogDebug("Request channel with id {channelId}", channelId); var foundChannel = channelServer.GetChannel(channelId); actionResult = await route.ActionInvoker.Value.InvokeChannel(actionContext, (MazeChannel)foundChannel); break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception e) { if (context.RequestAborted.IsCancellationRequested) { return; } _logger.LogError(e, $"Error occurred when invoking method {route.RouteMethod} of package {result.RouteDescription.PackageIdentity} (path: {context.Request.Path})"); await WriteError(context, BusinessErrors.Commander.ActionError(e.GetType().Name, route.RouteMethod.Name, e.Message), StatusCodes.Status500InternalServerError); return; } if (context.RequestAborted.IsCancellationRequested) { return; } try { await actionResult.ExecuteResultAsync(actionContext); } catch (Exception e) { if (context.RequestAborted.IsCancellationRequested) { return; } _logger.LogError(e, $"Error occurred when executing action result {route.RouteMethod} of package {result.RouteDescription.PackageIdentity} (path: {context.Request.Path})"); await WriteError(context, BusinessErrors.Commander.ResultExecutionError(e.GetType().Name, actionResult?.GetType().Name, e.Message), StatusCodes.Status500InternalServerError); return; } _logger.LogDebug("Request successfully executed."); }