示例#1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UriTemplateRouteResolver"/> class.
 /// </summary>
 /// <param name="inner">The inner.</param>
 /// <param name="moduleCatalog">The module catalog.</param>
 /// <param name="builder">The builder.</param>
 /// <param name="environment">The environment.</param>
 public UriTemplateRouteResolver(DefaultRouteResolver inner, INancyModuleCatalog moduleCatalog, INancyModuleBuilder builder, INancyEnvironment environment)
 {
     this.inner                     = inner;
     this.moduleCatalog             = moduleCatalog;
     this.builder                   = builder;
     this.globalizationConfiguraton = environment.GetValue <GlobalizationConfiguration>();
 }
示例#2
0
 public AlreadyKnownRouteResolver(INancyEnvironment environment, nancyrouting.Route route, INancyModule module, nancyrouting.Trie.MatchResult matchResult)
 {
     _globalizationConfiguraton = environment.GetValue <GlobalizationConfiguration>();
     _route       = route;
     _module      = module;
     _matchResult = matchResult;
 }
示例#3
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
 /// </summary>
 /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
 public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
 {
     this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog);
     this.viewRenderer          = new CSharpRazorViewRenderer(this.razorAssemblyProvider);
     this.razorConfiguration    = configuration;
     this.traceConfiguration    = environment.GetValue <TraceConfiguration>();
     this.AddDefaultNameSpaces(this.viewRenderer.Host);
 }
示例#4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
 /// </summary>
 /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
 public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
 {
     this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog);
     this.viewRenderer = new CSharpRazorViewRenderer(this.razorAssemblyProvider);
     this.razorConfiguration = configuration;
     this.traceConfiguration = environment.GetValue<TraceConfiguration>();
     this.AddDefaultNameSpaces(this.viewRenderer.Host);
 }
示例#5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultViewLocator"/> class.
 /// </summary>
 /// <param name="viewLocationProvider">An <see cref="IViewLocationProvider"/> instance.</param>
 /// <param name="viewEngines">An <see cref="IEnumerable{T}"/> of <see cref="IViewEngine"/> instances.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultViewLocator(IViewLocationProvider viewLocationProvider, IEnumerable <IViewEngine> viewEngines, INancyEnvironment environment)
 {
     this.viewLocationProvider = viewLocationProvider;
     this.viewEngines          = viewEngines;
     this.invalidCharacters    = Path.GetInvalidFileNameChars().Where(c => c != '/').ToArray();
     this.viewLocationResults  = new List <ViewLocationResult>(this.GetInititialViewLocations());
     this.configuration        = environment.GetValue <ViewConfiguration>();
 }
示例#6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultViewLocator"/> class.
 /// </summary>
 /// <param name="viewLocationProvider">An <see cref="IViewLocationProvider"/> instance.</param>
 /// <param name="viewEngines">An <see cref="IEnumerable{T}"/> of <see cref="IViewEngine"/> instances.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultViewLocator(IViewLocationProvider viewLocationProvider, IEnumerable<IViewEngine> viewEngines, INancyEnvironment environment)
 {
     this.viewLocationProvider = viewLocationProvider;
     this.viewEngines = viewEngines;
     this.invalidCharacters = Path.GetInvalidFileNameChars().Where(c => c != '/').ToArray();
     this.viewLocationResults = new List<ViewLocationResult>(this.GetInititialViewLocations());
     this.configuration = environment.GetValue<ViewConfiguration>();
 }
示例#7
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided <see cref="viewEngineStartupContext"/> instance.
        /// </summary>
        /// <param name="viewEngineStartupContext">A <see cref="ViewEngineStartupContext"/> instance.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext, INancyEnvironment environment)
        {
            this.viewEngineStartupContext = viewEngineStartupContext;
            this.configuration = environment.GetValue<ViewConfiguration>();

            // No need to lock here
            this.currentlyLocatedViews =
                new List<ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews());
        }
示例#8
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided <see cref="viewEngineStartupContext"/> instance.
        /// </summary>
        /// <param name="viewEngineStartupContext">A <see cref="ViewEngineStartupContext"/> instance.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext, INancyEnvironment environment)
        {
            this.viewEngineStartupContext = viewEngineStartupContext;
            this.configuration            = environment.GetValue <ViewConfiguration>();

            // No need to lock here
            this.currentlyLocatedViews =
                new List <ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews());
        }
示例#9
0
        /// <summary>
        /// Enable JSONP support in the application
        /// </summary>
        /// <param name="pipelines">Application Pipeline to Hook into</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public static void Enable(IPipelines pipelines, INancyEnvironment environment)
        {
            var jsonpEnabled = pipelines.AfterRequest.PipelineItems.Any(ctx => ctx.Name == "JSONP");

            if (!jsonpEnabled)
            {
                encoding = environment.GetValue <JsonConfiguration>().DefaultEncoding;
                pipelines.AfterRequest.AddItemToEndOfPipeline(JsonpItem);
            }
        }
示例#10
0
文件: Jsonp.cs 项目: RadifMasud/Nancy
        /// <summary>
        /// Enable JSONP support in the application
        /// </summary>
        /// <param name="pipelines">Application Pipeline to Hook into</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public static void Enable(IPipelines pipelines, INancyEnvironment environment)
        {
            var jsonpEnabled = pipelines.AfterRequest.PipelineItems.Any(ctx => ctx.Name == "JSONP");

            if (!jsonpEnabled)
            {
                encoding = environment.GetValue<JsonConfiguration>().DefaultEncoding;
                pipelines.AfterRequest.AddItemToEndOfPipeline(JsonpItem);
            }
        }
示例#11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultRouteResolver"/> class, using
        /// the provided <paramref name="catalog"/>, <paramref name="moduleBuilder"/>,
        /// <paramref name="routeCache"/> and <paramref name="trie"/>.
        /// </summary>
        /// <param name="catalog">An <see cref="INancyModuleCatalog"/> instance.</param>
        /// <param name="moduleBuilder">An <see cref="INancyModuleBuilder"/> instance.</param>
        /// <param name="routeCache">An <see cref="IRouteCache"/> instance.</param>
        /// <param name="trie">An <see cref="IRouteResolverTrie"/> instance.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultRouteResolver(INancyModuleCatalog catalog, INancyModuleBuilder moduleBuilder, IRouteCache routeCache, IRouteResolverTrie trie, INancyEnvironment environment)
        {
            this.catalog                   = catalog;
            this.moduleBuilder             = moduleBuilder;
            this.routeCache                = routeCache;
            this.trie                      = trie;
            this.configuration             = new Lazy <RouteConfiguration>(environment.GetValue <RouteConfiguration>);
            this.globalizationConfiguraton = environment.GetValue <GlobalizationConfiguration>();

            this.BuildTrie();
        }
示例#12
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultRouteResolver"/> class, using
        /// the provided <paramref name="catalog"/>, <paramref name="moduleBuilder"/>,
        /// <paramref name="routeCache"/> and <paramref name="trie"/>.
        /// </summary>
        /// <param name="catalog">An <see cref="INancyModuleCatalog"/> instance.</param>
        /// <param name="moduleBuilder">An <see cref="INancyModuleBuilder"/> instance.</param>
        /// <param name="routeCache">An <see cref="IRouteCache"/> instance.</param>
        /// <param name="trie">An <see cref="IRouteResolverTrie"/> instance.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultRouteResolver(INancyModuleCatalog catalog, INancyModuleBuilder moduleBuilder, IRouteCache routeCache, IRouteResolverTrie trie, INancyEnvironment environment)
        {
            this.catalog = catalog;
            this.moduleBuilder = moduleBuilder;
            this.routeCache = routeCache;
            this.trie = trie;
            this.configuration = new Lazy<RouteConfiguration>(environment.GetValue<RouteConfiguration>);
            this.globalizationConfiguraton = environment.GetValue<GlobalizationConfiguration>();

            this.BuildTrie();
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonResponse{TModel}"/> class,
        /// with the provided <paramref name="model"/>, <paramref name="serializer"/>
        /// and <paramref name="environment"/>.
        /// </summary>
        /// <param name="model">The model that should be returned as JSON.</param>
        /// <param name="serializer">The <see cref="ISerializer"/> to use for the serialization.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public JsonResponse(TModel model, ISerializer serializer, INancyEnvironment environment)
        {
            if (serializer == null)
            {
                throw new InvalidOperationException("JSON Serializer not set");
            }

            this.configuration = environment.GetValue <JsonConfiguration>();
            this.Contents      = model == null ? NoBody : this.GetJsonContents(model, serializer);
            this.ContentType   = this.DefaultContentType;
            this.StatusCode    = HttpStatusCode.OK;
        }
示例#14
0
        public XmlResponse(TModel model, ISerializer serializer, INancyEnvironment environment)
        {
            if (serializer == null)
            {
                throw new InvalidOperationException("XML Serializer not set");
            }

            this.configuration = environment.GetValue <XmlConfiguration>();

            this.Contents    = GetXmlContents(model, serializer);
            this.ContentType = DefaultContentType;
            this.StatusCode  = HttpStatusCode.OK;
        }
示例#15
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
        /// </summary>
        /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment)
        {
            this.viewRenderers = new List<IRazorViewRenderer>
            {
                new CSharpRazorViewRenderer(),
                new VisualBasicRazorViewRenderer()
            };

            this.razorConfiguration = configuration;
            this.traceConfiguration = environment.GetValue<TraceConfiguration>();

            foreach (var renderer in this.viewRenderers)
            {
                this.AddDefaultNameSpaces(renderer.Host);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        /// <param name="negotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyEngine(IRequestDispatcher dispatcher,
                           INancyContextFactory contextFactory,
                           IEnumerable <IStatusCodeHandler> statusCodeHandlers,
                           IRequestTracing requestTracing,
                           IStaticContentProvider staticContentProvider,
                           IResponseNegotiator negotiator,
                           INancyEnvironment environment)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            if (negotiator == null)
            {
                throw new ArgumentNullException("negotiator");
            }

            this.dispatcher            = dispatcher;
            this.contextFactory        = contextFactory;
            this.statusCodeHandlers    = statusCodeHandlers.ToArray();
            this.requestTracing        = requestTracing;
            this.staticContentProvider = staticContentProvider;
            this.negotiator            = negotiator;
            this.engineDisposedCts     = new CancellationTokenSource();
            this.traceConfiguration    = environment.GetValue <TraceConfiguration>();
        }
示例#17
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultStatusCodeHandler"/> type.
        /// </summary>
        /// <param name="responseNegotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment)
        {
            this.errorMessages = new Dictionary<HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, "The resource you have requested cannot be found." },
                { HttpStatusCode.InternalServerError, "Something went horribly, horribly wrong while servicing your request." }
            };

            this.errorPages = new Dictionary<HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, LoadResource("404.html") },
                { HttpStatusCode.InternalServerError, LoadResource("500.html") }
            };

            this.responseNegotiator = responseNegotiator;
            this.configuration = environment.GetValue<TraceConfiguration>();
        }
示例#18
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine"/> class.
        /// </summary>
        /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param>
        public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog)
        {
            this.viewRenderers = new List <IRazorViewRenderer>
            {
                new CSharpRazorViewRenderer(assemblyCatalog),
                new VisualBasicRazorViewRenderer(assemblyCatalog)
            };

            this.razorConfiguration = configuration;
            this.assemblyCatalog    = assemblyCatalog;
            this.traceConfiguration = environment.GetValue <TraceConfiguration>();

            foreach (var renderer in this.viewRenderers)
            {
                this.AddDefaultNameSpaces(renderer.Host);
            }
        }
示例#19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultStatusCodeHandler"/> type.
        /// </summary>
        /// <param name="responseNegotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment)
        {
            this.errorMessages = new Dictionary <HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, "The resource you have requested cannot be found." },
                { HttpStatusCode.InternalServerError, "Something went horribly, horribly wrong while servicing your request." }
            };

            this.errorPages = new Dictionary <HttpStatusCode, string>
            {
                { HttpStatusCode.NotFound, LoadResource("404.html") },
                { HttpStatusCode.InternalServerError, LoadResource("500.html") }
            };

            this.responseNegotiator = responseNegotiator;
            this.configuration      = environment.GetValue <TraceConfiguration>();
        }
示例#20
0
        public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog)
            : base("/info")
        {
            this.typeCatalog = typeCatalog;

            Get["/"] = async (_, __) =>
            {
                return View["Info"];
            };

            Get["/data"] = async (_, __) =>
            {
                dynamic data = new ExpandoObject();



                data.Nancy = new ExpandoObject();
                data.Nancy.Version = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString());
                data.Nancy.TracesDisabled = !environment.GetValue<TraceConfiguration>().DisplayErrorTraces;
                data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive";
                data.Nancy.RootPath = rootPathProvider.GetRootPath();
                data.Nancy.Hosting = GetHosting();
                data.Nancy.BootstrapperContainer = GetBootstrapperContainer();
                data.Nancy.LocatedBootstrapper = NancyBootstrapperLocator.Bootstrapper.GetType().ToString();
                data.Nancy.LoadedViewEngines = GetViewEngines();

                data.Configuration = new Dictionary<string, object>();
                foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    var value =
                        propertyInfo.GetValue(configuration, null);

                    data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ?
                        new[] { value.ToString() } :
                        ((IEnumerable<object>)value).Select(x => x.ToString());
                }

                return this.Response.AsJson((object)data);
            };
        }
示例#21
0
        public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog)
            : base("/info")
        {
            this.typeCatalog = typeCatalog;

            Get["/"] = async(_, __) =>
            {
                return(View["Info"]);
            };

            Get["/data"] = async(_, __) =>
            {
                dynamic data = new ExpandoObject();



                data.Nancy                       = new ExpandoObject();
                data.Nancy.Version               = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString());
                data.Nancy.TracesDisabled        = !environment.GetValue <TraceConfiguration>().DisplayErrorTraces;
                data.Nancy.CaseSensitivity       = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive";
                data.Nancy.RootPath              = rootPathProvider.GetRootPath();
                data.Nancy.Hosting               = GetHosting();
                data.Nancy.BootstrapperContainer = GetBootstrapperContainer();
                data.Nancy.LocatedBootstrapper   = NancyBootstrapperLocator.Bootstrapper.GetType().ToString();
                data.Nancy.LoadedViewEngines     = GetViewEngines();

                data.Configuration = new Dictionary <string, object>();
                foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    var value =
                        propertyInfo.GetValue(configuration, null);

                    data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ?
                                                            new[] { value.ToString() } :
                    ((IEnumerable <object>)value).Select(x => x.ToString());
                }

                return(this.Response.AsJson((object)data));
            };
        }
示例#22
0
 /// <summary>
 /// Creates a new instance of DefaultCultureService
 /// </summary>
 /// <param name="cultureConventions">CultureConventions to use for determining culture</param>
 /// <param name="environment">An instance of <see cref="INancyEnvironment"/> to retrieve <see cref="GlobalizationConfiguration"/> from.</param>
 public DefaultCultureService(CultureConventions cultureConventions, INancyEnvironment environment)
 {
     this.cultureConventions = cultureConventions;
     this.configuration = environment.GetValue<GlobalizationConfiguration>();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="FavIconApplicationStartup"/> class, with the
 /// provided <see cref="IRootPathProvider"/> instance.
 /// </summary>
 /// <param name="rootPathProvider">The <see cref="IRootPathProvider"/> that should be used to scan for a favicon.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public FavIconApplicationStartup(IRootPathProvider rootPathProvider, INancyEnvironment environment)
 {
     FavIconApplicationStartup.rootPathProvider   = rootPathProvider;
     FavIconApplicationStartup.traceConfiguration = environment.GetValue <TraceConfiguration>();
 }
示例#24
0
 /// <summary>
 /// Creates a new instance of DefaultCultureService
 /// </summary>
 /// <param name="cultureConventions">CultureConventions to use for determining culture</param>
 /// <param name="environment">An instance of <see cref="INancyEnvironment"/> to retrieve <see cref="GlobalizationConfiguration"/> from.</param>
 public DefaultCultureService(CultureConventions cultureConventions, INancyEnvironment environment)
 {
     this.cultureConventions = cultureConventions;
     this.configuration      = environment.GetValue <GlobalizationConfiguration>();
 }
示例#25
0
        /// <summary>
        /// Initializes a new instance of the <see cref="NancyEngine"/> class.
        /// </summary>
        /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param>
        /// <param name="contextFactory">A factory for creating contexts</param>
        /// <param name="statusCodeHandlers">Error handlers</param>
        /// <param name="requestTracing">The request tracing instance.</param>
        /// <param name="staticContentProvider">The provider to use for serving static content</param>
        /// <param name="negotiator">The response negotiator.</param>
        /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
        public NancyEngine(IRequestDispatcher dispatcher,
            INancyContextFactory contextFactory,
            IEnumerable<IStatusCodeHandler> statusCodeHandlers,
            IRequestTracing requestTracing,
            IStaticContentProvider staticContentProvider,
            IResponseNegotiator negotiator,
            INancyEnvironment environment)
        {
            if (dispatcher == null)
            {
                throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null.");
            }

            if (contextFactory == null)
            {
                throw new ArgumentNullException("contextFactory");
            }

            if (statusCodeHandlers == null)
            {
                throw new ArgumentNullException("statusCodeHandlers");
            }

            if (requestTracing == null)
            {
                throw new ArgumentNullException("requestTracing");
            }

            if (staticContentProvider == null)
            {
                throw new ArgumentNullException("staticContentProvider");
            }

            if (negotiator == null)
            {
                throw new ArgumentNullException("negotiator");
            }

            this.dispatcher = dispatcher;
            this.contextFactory = contextFactory;
            this.statusCodeHandlers = statusCodeHandlers.ToArray();
            this.requestTracing = requestTracing;
            this.staticContentProvider = staticContentProvider;
            this.negotiator = negotiator;
            this.engineDisposedCts = new CancellationTokenSource();
            this.traceConfiguration = environment.GetValue<TraceConfiguration>();
        }
示例#26
0
        /// <summary>
        /// Enables the diagnostics dashboard and will intercept all requests that are passed to
        /// the condigured paths.
        /// </summary>
        public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable<IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment)
        {
            var diagnosticsConfiguration =
                environment.GetValue<DiagnosticsConfiguration>();

            var diagnosticsEnvironment =
                GetDiagnosticsEnvironment();

            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment);

            var diagnosticsRouteCache = new RouteCache(
                diagnosticsModuleCatalog,
                new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource),
                new DefaultRouteSegmentExtractor(),
                new DefaultRouteDescriptionProvider(),
                cultureService,
                routeMetadataProviders);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment),
                diagnosticsRouteCache,
                new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)));

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem<Func<NancyContext, Response>>(
                    PipelineKey,
                    ctx =>
                    {
                        if (!ctx.ControlPanelEnabled)
                        {
                            return null;
                        }

                        if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                        {
                            return null;
                        }

                        ctx.Items[ItemsKey] = true;

                        var resourcePrefix =
                            string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                        if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                        {
                            var resourceNamespace = "Nancy.Diagnostics.Resources";

                            var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                            if (!string.IsNullOrEmpty(path))
                            {
                                resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
                            }

                            return new EmbeddedFileResponse(
                                typeof(DiagnosticsHook).Assembly,
                                resourceNamespace,
                                Path.GetFileName(ctx.Request.Url.Path));
                        }

                        RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                        return ValidateConfiguration(diagnosticsConfiguration)
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx);
                    }));
        }
示例#27
0
        public MainModule(IRouteCacheProvider routeCacheProvider, INancyEnvironment environment)
        {
            Get["/"] = x => {
                return View["routes", routeCacheProvider.GetCache()];
            };

            Get["/texts"] = parameters => {
                return (string)this.Context.Text.Menu.Home;
            };

            Get["/env"] = _ =>
            {
                return "From nancy environment: " + environment.GetValue<MyConfig>().Value;
            };

            Get["/meta"] = parameters =>
            {
                return Negotiate
                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyRouteMetadata>())
                    .WithView("meta");
            };

            Get["/uber-meta"] = parameters =>
            {
                return Negotiate
                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyUberRouteMetadata>().OfType<MyUberRouteMetadata>())
                    .WithView("uber-meta");
            };

            Get["/text"] = x =>
            {
                var value = (string)this.Context.Text.Menu.Home;
                return string.Concat("Value of 'Home' resource key in the Menu resource file: ", value);
            };

            Get["/negotiated"] = parameters => {
                return Negotiate
                    .WithModel(new RatPack {FirstName = "Nancy "})
                    .WithMediaRangeModel("text/html", new RatPack {FirstName = "Nancy fancy pants"})
                    .WithView("negotiatedview")
                    .WithHeader("X-Custom", "SomeValue");
            };

            Get["/user/{name}"] = parameters =>
            {
                return (string)parameters.name;
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/nustache"] = parameters => {
                return View["nustache", new { name = "Nancy", value = 1000000 }];
            };

            Get["/dotliquid"] = parameters => {
                return View["dot", new { name = "dot" }];
            };

            Get["/javascript"] = x => {
                return View["javascript.html"];
            };

            Get["/static"] = x => {
                return View["static"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor.cshtml", model];
            };

            Get["/razor-divzero"] = x =>
            {
                var model = new { FirstName = "Frank", Number = 22 };
                return View["razor-divzero.cshtml", model];
            };

            Get["/razorError"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-error.cshtml", model];
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-simple.cshtml", model];
            };

            Get["/razor-dynamic"] = x =>
            {
                return View["razor.cshtml", new { FirstName = "Frank" }];
            };

            Get["/razor-cs-strong"] = x =>
            {
                return View["razor-strong.cshtml", new RatPack { FirstName = "Frank" }];
            };

            Get["/razor-vb-strong"] = x =>
            {
                return View["razor-strong.vbhtml", new RatPack { FirstName = "Frank" }];
            };

            Get["/razor2"] = _ => new Razor2();

            Get["/ssve"] = x =>
            {
                var model = new RatPack { FirstName = "You" };
                return View["ssve.sshtml", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["spark.spark", model];
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return View["anon.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return this.Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return this.Response.AsXml(model);
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return output;
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };

            Get["/error"] = x =>
                {
                    throw new NotSupportedException("This is an exception thrown in a route.");
                };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return string.Format("Hello {0}!", this.Request.Form.Name);
            };

            Get["/csrfWithExpiry"] = x =>
                {
                    // Create a new one because we have an expiry to check
                    this.CreateNewCsrfToken();

                    return this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }];
                };

            Post["/csrfWithExpiry"] = x =>
                {
                    this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                    return string.Format("Hello {0}!", this.Request.Form.Name);
                };

            Get["/viewNotFound"] = _ => View["I-do-not-exist"];

            Get["/fileupload"] = x =>
            {
                return View["FileUpload", new { Posted = "Nothing" }];
            };

            Post["/fileupload"] = x =>
            {
                var file = this.Request.Files.FirstOrDefault();

                string fileDetails = "Nothing";

                if (file != null)
                {
                    fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key);
                }

                return View["FileUpload", new { Posted = fileDetails }];
            };

            Get["NamedRoute", "/namedRoute"] = _ => "I am a named route!";
        }
示例#28
0
        public MainModule(IRouteCacheProvider routeCacheProvider, INancyEnvironment environment)
        {
            Get["/"] = x => {
                return(View["routes", routeCacheProvider.GetCache()]);
            };

            Get["/texts"] = parameters => {
                return((string)this.Context.Text.Menu.Home);
            };

            Get["/env"] = _ =>
            {
                return("From nancy environment: " + environment.GetValue <MyConfig>().Value);
            };

            Get["/meta"] = parameters =>
            {
                return(Negotiate
                       .WithModel(routeCacheProvider.GetCache().RetrieveMetadata <MyRouteMetadata>())
                       .WithView("meta"));
            };

            Get["/uber-meta"] = parameters =>
            {
                return(Negotiate
                       .WithModel(routeCacheProvider.GetCache().RetrieveMetadata <MyUberRouteMetadata>().OfType <MyUberRouteMetadata>())
                       .WithView("uber-meta"));
            };

            Get["/text"] = x =>
            {
                var value = (string)this.Context.Text.Menu.Home;
                return(string.Concat("Value of 'Home' resource key in the Menu resource file: ", value));
            };

            Get["/negotiated"] = parameters => {
                return(Negotiate
                       .WithModel(new RatPack {
                    FirstName = "Nancy "
                })
                       .WithMediaRangeModel("text/html", new RatPack {
                    FirstName = "Nancy fancy pants"
                })
                       .WithView("negotiatedview")
                       .WithHeader("X-Custom", "SomeValue"));
            };

            Get["/user/{name}"] = parameters =>
            {
                return((string)parameters.name);
            };

            Get["/filtered", r => true] = x => {
                return("This is a route with a filter that always returns true.");
            };

            Get["/filtered", r => false] = x => {
                return("This is also a route, but filtered out so should never be hit.");
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return(string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar));
            };

            Get["/test"] = x => {
                return("Test");
            };

            Get["/nustache"] = parameters => {
                return(View["nustache", new { name = "Nancy", value = 1000000 }]);
            };

            Get["/dotliquid"] = parameters => {
                return(View["dot", new { name = "dot" }]);
            };

            Get["/javascript"] = x => {
                return(View["javascript.html"]);
            };

            Get["/static"] = x => {
                return(View["static"]);
            };

            Get["/razor"] = x => {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor.cshtml", model]);
            };

            Get["/razor-divzero"] = x =>
            {
                var model = new { FirstName = "Frank", Number = 22 };
                return(View["razor-divzero.cshtml", model]);
            };

            Get["/razorError"] = x =>
            {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor-error.cshtml", model]);
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor-simple.cshtml", model]);
            };

            Get["/razor-dynamic"] = x =>
            {
                return(View["razor.cshtml", new { FirstName = "Frank" }]);
            };

            Get["/razor-cs-strong"] = x =>
            {
                return(View["razor-strong.cshtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/razor-vb-strong"] = x =>
            {
                return(View["razor-strong.vbhtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/razor2"] = _ => new Razor2();

            Get["/ssve"] = x =>
            {
                var model = new RatPack {
                    FirstName = "You"
                };
                return(View["ssve.sshtml", model]);
            };

            Get["/viewmodelconvention"] = x => {
                return(View[new SomeViewModel()]);
            };

            Get["/spark"] = x => {
                var model = new RatPack {
                    FirstName = "Bright"
                };
                return(View["spark.spark", model]);
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return(View["anon.spark", model]);
            };

            Get["/json"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(this.Response.AsJson(model));
            };

            Get["/xml"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(this.Response.AsXml(model));
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (string.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return(output);
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return(output);
            };

            Get["/error"] = x =>
            {
                throw new NotSupportedException("This is an exception thrown in a route.");
            };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return(string.Format("Hello {0}!", this.Request.Form.Name));
            };

            Get["/csrfWithExpiry"] = x =>
            {
                // Create a new one because we have an expiry to check
                this.CreateNewCsrfToken();

                return(this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }]);
            };

            Post["/csrfWithExpiry"] = x =>
            {
                this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                return(string.Format("Hello {0}!", this.Request.Form.Name));
            };

            Get["/viewNotFound"] = _ => View["I-do-not-exist"];

            Get["/fileupload"] = x =>
            {
                return(View["FileUpload", new { Posted = "Nothing" }]);
            };

            Post["/fileupload"] = x =>
            {
                var file = this.Request.Files.FirstOrDefault();

                string fileDetails = "Nothing";

                if (file != null)
                {
                    fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key);
                }

                return(View["FileUpload", new { Posted = fileDetails }]);
            };

            Get["NamedRoute", "/namedRoute"] = _ => "I am a named route!";
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="FavIconApplicationStartup"/> class, with the
 /// provided <see cref="IRootPathProvider"/> instance.
 /// </summary>
 /// <param name="rootPathProvider">The <see cref="IRootPathProvider"/> that should be used to scan for a favicon.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public FavIconApplicationStartup(IRootPathProvider rootPathProvider, INancyEnvironment environment)
 {
     FavIconApplicationStartup.rootPathProvider = rootPathProvider;
     FavIconApplicationStartup.traceConfiguration = environment.GetValue<TraceConfiguration>();
 }
示例#30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewProcessor"/> class,
 /// with the provided <paramref name="viewFactory"/>.
 /// </summary>
 /// <param name="viewFactory">The view factory that should be used to render views.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public ViewProcessor(IViewFactory viewFactory, INancyEnvironment environment)
 {
     this.viewFactory = viewFactory;
     this.traceConfiguration = environment.GetValue<TraceConfiguration>();
 }
示例#31
0
        public static void Enable(IPipelines pipelines, IEnumerable <IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors, IEnumerable <IRouteSegmentConstraint> routeSegmentConstraints, ICultureService cultureService, IRequestTraceFactory requestTraceFactory, IEnumerable <IRouteMetadataProvider> routeMetadataProviders, ITextResource textResource, INancyEnvironment environment)
        {
            var diagnosticsConfiguration =
                environment.GetValue <DiagnosticsConfiguration>();

            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);

            var diagnosticsRouteCache = new RouteCache(
                diagnosticsModuleCatalog,
                new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource),
                new DefaultRouteSegmentExtractor(),
                new DefaultRouteDescriptionProvider(),
                cultureService,
                routeMetadataProviders);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, environment),
                diagnosticsRouteCache,
                new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints)));

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem <Func <NancyContext, Response> >(
                    PipelineKey,
                    ctx =>
            {
                if (!ctx.ControlPanelEnabled)
                {
                    return(null);
                }

                if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                {
                    return(null);
                }

                ctx.Items[ItemsKey] = true;

                var resourcePrefix =
                    string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                {
                    var resourceNamespace = "Nancy.Diagnostics.Resources";

                    var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                    if (!string.IsNullOrEmpty(path))
                    {
                        resourceNamespace += string.Format(".{0}", path.Replace(Path.DirectorySeparatorChar, '.'));
                    }

                    return(new EmbeddedFileResponse(
                               typeof(DiagnosticsHook).Assembly,
                               resourceNamespace,
                               Path.GetFileName(ctx.Request.Url.Path)));
                }

                RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                return(ValidateConfiguration(diagnosticsConfiguration)
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx));
            }));
        }
示例#32
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewProcessor"/> class,
 /// with the provided <paramref name="viewFactory"/>.
 /// </summary>
 /// <param name="viewFactory">The view factory that should be used to render views.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public ViewProcessor(IViewFactory viewFactory, INancyEnvironment environment)
 {
     this.viewFactory        = viewFactory;
     this.traceConfiguration = environment.GetValue <TraceConfiguration>();
 }
示例#33
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonBodyDeserializer"/>,
 /// with the provided <paramref name="environment"/>.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public JsonBodyDeserializer(INancyEnvironment environment)
 {
     this.configuration = environment.GetValue<JsonConfiguration>();
 }
示例#34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultRequestTraceFactory"/> class.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultRequestTraceFactory(INancyEnvironment environment)
 {
     this.configuration = environment.GetValue <TraceConfiguration>();
 }
 /// <summary>
 /// Gets a value from the environment, using the full name of the type defined by <typeparamref name="T"/> as the key.
 /// </summary>
 /// <param name="environment">The <see cref="INancyEnvironment"/> instance.</param>
 /// <typeparam name="T">The <see cref="Type"/> of the value to retreive from the environment.</typeparam>
 /// <returns></returns>
 public static T GetValue <T>(this INancyEnvironment environment)
 {
     return(environment.GetValue <T>(typeof(T).FullName));
 }
示例#36
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultXmlSerializer"/> class,
 /// with the provided <see cref="INancyEnvironment"/>.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultXmlSerializer(INancyEnvironment environment)
 {
     this.configuration      = environment.GetValue <XmlConfiguration>();
     this.traceConfiguration = environment.GetValue <TraceConfiguration>();
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultRequestTraceFactory"/> class.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultRequestTraceFactory(INancyEnvironment environment)
 {
     this.configuration = environment.GetValue<TraceConfiguration>();
 }
示例#38
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultViewCache"/> class.
 /// </summary>
 public DefaultViewCache(INancyEnvironment environment)
 {
     this.cache         = new ConcurrentDictionary <ViewLocationResult, object>();
     this.configuration = environment.GetValue <ViewConfiguration>();
 }
示例#39
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultJsonSerializer"/> class,
 /// with the provided <see cref="INancyEnvironment"/>.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultJsonSerializer(INancyEnvironment environment)
 {
     this.jsonConfiguration  = environment.GetValue <JsonConfiguration>();
     this.traceConfiguration = environment.GetValue <TraceConfiguration>();
 }
示例#40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="JsonBodyDeserializer"/>,
 /// with the provided <paramref name="environment"/>.
 /// </summary>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public JsonBodyDeserializer(INancyEnvironment environment)
 {
     this.jsonConfiguration          = environment.GetValue <JsonConfiguration>();
     this.globalizationConfiguration = environment.GetValue <GlobalizationConfiguration>();
 }