Esempio n. 1
0
        public void Register(IAppHost appHost)
        {
            var contentTypes     = appHost.ContentTypes;
            var predefinedRoutes = appHost.GetPlugin <PredefinedRoutesFeature>();

            if (predefinedRoutes == null)
            {
                throw new NotSupportedException("SoapFormat requires the PredefinedRoutesFeature Plugin");
            }

            if (!DisableSoap11)
            {
                contentTypes.Register(MimeTypes.Soap11, SoapHandler.SerializeSoap11ToStream, null);
                contentTypes.ContentTypeStringSerializers[MimeTypes.Soap11] = (r, o) =>
                                                                              SoapHandler.SerializeSoap11ToBytes(r, o).FromUtf8Bytes();

                var soap11 = ContentFormat.GetContentFormat(Format.Soap11);
                predefinedRoutes.HandlerMappings[soap11] = () => new Soap11MessageReplyHttpHandler();
            }

            if (!DisableSoap12)
            {
                contentTypes.Register(MimeTypes.Soap12, SoapHandler.SerializeSoap12ToStream, null);
                contentTypes.ContentTypeStringSerializers[MimeTypes.Soap12] = (r, o) =>
                                                                              SoapHandler.SerializeSoap12ToBytes(r, o).FromUtf8Bytes();

                var soap12 = ContentFormat.GetContentFormat(Format.Soap12);
                predefinedRoutes.HandlerMappings[soap12] = () => new Soap12MessageReplyHttpHandler();
            }

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/soap-support", "SOAP support");
        }
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService <RequestLogsService>(AtRestPath);

            var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity);

            requestLogger.EnableSessionTracking     = EnableSessionTracking;
            requestLogger.EnableResponseTracking    = EnableResponseTracking;
            requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
            requestLogger.LimitToServiceRequests    = LimitToServiceRequests;
            requestLogger.SkipLogging                       = SkipLogging;
            requestLogger.RequiredRoles                     = RequiredRoles;
            requestLogger.EnableErrorTracking               = EnableErrorTracking;
            requestLogger.ExcludeRequestDtoTypes            = ExcludeRequestDtoTypes;
            requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;

            appHost.Register(requestLogger);

            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) =>
                {
                    httpReq.UseBufferedStream = EnableRequestBodyTracking;
                });
            }

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.DebugInfo, AtRestPath.TrimStart('/'), "Request Logs");
            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/request-logger", "Request Logger");
        }
        public void Register(IAppHost appHost)
        {
            appHost.RawHttpHandlers.Add(GetRequestInfoHandler);
            appHost.CatchAllHandlers.Add(GetRequestInfoHandler);

            appHost.GetPlugin <MetadataFeature>()?
            .AddLink(MetadataFeature.DebugInfo, $"?{Keywords.Debug}={Keywords.RequestInfo}", "Request Info");
            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/debugging#request-info", "Request Info");
        }
        public void Register(IAppHost appHost)
        {
            if (!string.IsNullOrEmpty(AtRestPath))
            {
                appHost.RegisterService <RequestLogsService>(AtRestPath);
            }

            var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity);

            requestLogger.EnableSessionTracking     = EnableSessionTracking;
            requestLogger.EnableResponseTracking    = EnableResponseTracking;
            requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
            requestLogger.LimitToServiceRequests    = LimitToServiceRequests;
            requestLogger.SkipLogging                       = SkipLogging;
            requestLogger.RequiredRoles                     = RequiredRoles;
            requestLogger.EnableErrorTracking               = EnableErrorTracking;
            requestLogger.ExcludeRequestDtoTypes            = ExcludeRequestDtoTypes;
            requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;
            requestLogger.RequestLogFilter                  = RequestLogFilter;
            requestLogger.IgnoreFilter                      = IgnoreFilter;
            requestLogger.CurrentDateFn                     = CurrentDateFn;

            appHost.Register(requestLogger);

            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) =>
                {
#if NETCORE
                    // https://forums.servicestack.net/t/unexpected-end-of-stream-when-uploading-to-aspnet-core/6478/6
                    if (httpReq.ContentType.MatchesContentType(MimeTypes.MultiPartFormData))
                    {
                        return;
                    }
#endif
                    httpReq.UseBufferedStream = EnableRequestBodyTracking;
                });
            }

            appHost.GetPlugin <MetadataFeature>()
            .AddDebugLink(AtRestPath, "Request Logs");

            appHost.GetPlugin <MetadataFeature>()?.ExportTypes.Add(typeof(RequestLogEntry));

            appHost.AddToAppMetadata(meta => {
                meta.Plugins.RequestLogs = new RequestLogsInfo {
                    RequiredRoles = RequiredRoles,
                    ServiceRoutes = new Dictionary <string, string[]> {
                        { nameof(RequestLogsService), new[] { AtRestPath } },
                    },
                    RequestLogger = requestLogger.GetType().Name,
                };
            });
        }
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService <PostmanService>(AtRestPath);

            if (EnableSessionExport == null)
            {
                EnableSessionExport = appHost.Config.DebugMode;
            }

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.PluginLinks, AtRestPath.TrimStart('/'), "Postman Metadata");
            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/postman", "Postman");
        }
Esempio n. 6
0
        public void Register(IAppHost appHost)
        {
            appHost.ContentTypes.Register(MimeTypes.ProtoBuf, Serialize, Deserialize);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/protobuf-format", "ProtoBuf Format");
        }
Esempio n. 7
0
        public void Register(IAppHost appHost)
        {
            appHost.CatchAllHandlers.Add(ProcessRequest);

            appHost.GetPlugin<MetadataFeature>()
                .AddDebugLink("?debug=requestinfo", "Request Info");
        }
Esempio n. 8
0
        public void Register(IAppHost appHost)
        {
            appHost.CatchAllHandlers.Add(ProcessRequest);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/routing#pre-defined-routes", "Pre-defined Routes");
        }
Esempio n. 9
0
        public void Register(IAppHost appHost)
        {
            appHost.CatchAllHandlers.Add(ProcessRequest);

            appHost.GetPlugin <MetadataFeature>()
            .AddDebugLink("?debug=requestinfo", "Request Info");
        }
Esempio n. 10
0
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService(typeof(CancellableRequestService), AtPath);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/cancellable-requests", "Cancellable Requests");
        }
        public async void Register(IAppHost appHost)
        {
            appSettings = appHost.AppSettings ?? new AppSettings();

            var connectionSettings = GetConnectionSettings();

            var eventStoreConnection = connection ?? EventStoreConnection.Create(connectionSettings.GetConnectionString());

            await eventStoreConnection.ConnectAsync().ConfigureAwait(false); //no need for the initial synchronisation context

            //to be reused when executing the rest of the method

            new ConnectionMonitor(eventStoreConnection, connectionSettings.MonitorSettings)
            .AddHandlers();

            container = appHost.GetContainer();

            RegisterTypesForIoc(eventStoreConnection);

            appHost.GetPlugin <MetadataFeature>()?
            .AddPluginLink($"http://{connectionSettings.GetHttpEndpoint()}/", "EventStore");

            try
            {
                foreach (var subscription in subscriptionSettings.Subscriptions)
                {
                    var consumer = (StreamConsumer)container.TryResolve(consumers[subscription.GetType().Name]);
                    await consumer.ConnectToSubscription(subscription).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                log.Error(e);
            }
        }
Esempio n. 12
0
        public void Register(IAppHost appHost)
        {
            appHost.CatchAllHandlers.Add(ProcessRequest);

            appHost.GetPlugin<MetadataFeature>()
                .AddDebugLink($"?{Keywords.Debug}={Keywords.RequestInfo}", "Request Info");
        }
Esempio n. 13
0
        public void Register(IAppHost appHost)
        {
            appHost.GlobalResponseFiltersAsync.Add(HandleCacheResponses);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/http-caching", "HTTP Caching");
        }
Esempio n. 14
0
        public void Register(IAppHost appHost)
        {
            appHost.RawHttpHandlers.Add(req =>
            {
                if (SitemapIndex.Count > 0)
                {
                    if (req.PathInfo == AtPath)
                    {
                        return(new SitemapIndexHandler(this));
                    }

                    foreach (var sitemap in SitemapIndex)
                    {
                        if (req.PathInfo == sitemap.AtPath)
                        {
                            return(new SitemapUrlSetHandler(this, sitemap.UrlSet));
                        }
                    }
                }
                else if (UrlSet.Count > 0)
                {
                    if (req.PathInfo == AtPath)
                    {
                        return(new SitemapUrlSetHandler(this, UrlSet));
                    }
                }

                return(null);
            });

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/sitemaps", "Sitemaps");
        }
Esempio n. 15
0
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService <RequestLogsService>(AtRestPath);

            var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity);

            requestLogger.EnableSessionTracking     = EnableSessionTracking;
            requestLogger.EnableResponseTracking    = EnableResponseTracking;
            requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
            requestLogger.SkipLogging                       = SkipLogging;
            requestLogger.RequiredRoles                     = RequiredRoles;
            requestLogger.EnableErrorTracking               = EnableErrorTracking;
            requestLogger.ExcludeRequestDtoTypes            = ExcludeRequestDtoTypes;
            requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;

            appHost.Register(requestLogger);

            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) =>
                {
                    httpReq.UseBufferedStream = EnableRequestBodyTracking;
                });
            }

            appHost.GetPlugin <MetadataFeature>()
            .AddDebugLink(AtRestPath, "Request Logs");
        }
Esempio n. 16
0
        public void Register(IAppHost appHost)
        {
            var indexFile = appHost.VirtualFileSources.GetFile("ss_admin/index.html");

            if (indexFile == null)
            {
                return; // not accessible when referenced as a source project
            }
            var indexHtml = indexFile.ReadAllText();

            appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
                                         pathInfo.StartsWith("/ss_admin")
                    ? (pathInfo == "/ss_admin/index.html" || !appHost.VirtualFileSources.FileExists(pathInfo)
                        ? new CustomActionHandlerAsync(async(req, res) => {
                res.ContentType = MimeTypes.Html;
                var html = indexHtml.Replace("/dist", req.ResolveAbsoluteUrl("~/ss_admin/dist"));
                if (!string.IsNullOrEmpty(InsertHtml))
                {
                    html = html.Replace("</body>", InsertHtml + "</body>");
                }
                await res.WriteAsync(html);
            }) as IHttpHandler
                        : new StaticFileHandler(appHost.VirtualFileSources.GetFile(pathInfo)))
                    : null);

            appHost.GetPlugin <MetadataFeature>()
            .AddPluginLink("ss_admin/autoquery/", "AutoQuery Viewer");
        }
        public void Register(IAppHost appHost)
        {
            appHost.RawHttpHandlers.Add(MiniProfiler.UI.MiniProfilerHandler.MatchesRequest);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/built-in-profiling", "Built-in profiling");
        }
Esempio n. 18
0
        public void Register(IAppHost appHost)
        {
            appHost.CatchAllHandlers.Add(ProcessRequest);

            appHost.GetPlugin <MetadataFeature>()
            .AddDebugLink($"?{Keywords.Debug}={Keywords.RequestInfo}", "Request Info");
        }
Esempio n. 19
0
        public void Register(IAppHost appHost)
        {
            if (ShowDrivesLinks)
            {
                var diskFormat = Env.IsWindows ? "NTFS" : "ext2";
                appHost.GetPlugin <MetadataFeature>()
                .AddPluginLink("/drives", "All Disks")
                .AddPluginLink($"/drives?DriveFormatIn={diskFormat}", $"{diskFormat} Disks");
            }

            if (ShowProcessLinks)
            {
                appHost.GetPlugin <MetadataFeature>()
                .AddPluginLink("/processes", "All Processes")
                .AddPluginLink("/process/current", "Current Process");
            }
        }
Esempio n. 20
0
        public void Register(IAppHost appHost)
        {
            //Add permanent and session cookies if not already set.
            appHost.GlobalRequestFilters.Add(AddSessionIdToRequestFilter);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/sessions", "Sessions");
        }
        public void Register(IAppHost appHost)
        {
            appHost.ServiceExceptionHandlers.Add(HandleServiceException);
            appHost.UncaughtExceptionHandlers.Add(HandleUncaughtException);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/request-logger#redis-request-logger", nameof(RedisErrorLoggerFeature));
        }
Esempio n. 22
0
        public void Register(IAppHost appHost)
        {
            if (ResourceFilterPattern != null)
                SwaggerResourcesService.resourceFilterRegex = new Regex(ResourceFilterPattern, RegexOptions.Compiled);

            SwaggerApiService.UseCamelCaseModelPropertyNames = UseCamelCaseModelPropertyNames;
            SwaggerApiService.UseLowercaseUnderscoreModelPropertyNames = UseLowercaseUnderscoreModelPropertyNames;
            SwaggerApiService.DisableAutoDtoInBodyParam = DisableAutoDtoInBodyParam;
            SwaggerApiService.ModelFilter = ModelFilter;
            SwaggerApiService.ModelPropertyFilter = ModelPropertyFilter;

            appHost.RegisterService(typeof(SwaggerResourcesService), new[] { "/resources" });
            appHost.RegisterService(typeof(SwaggerApiService), new[] { SwaggerResourcesService.RESOURCE_PATH + "/{Name*}" });

            var swaggerUrl = UseBootstrapTheme
                ? "swagger-ui-bootstrap/"
                : "swagger-ui/";

            appHost.GetPlugin<MetadataFeature>()
                .AddPluginLink(swaggerUrl, "Swagger UI");

            appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
            {
                IVirtualFile indexFile;
                switch (pathInfo)
                {
                    case "/swagger-ui":
                    case "/swagger-ui/":
                    case "/swagger-ui/default.html":
                        indexFile = appHost.VirtualPathProvider.GetFile("/swagger-ui/index.html");
                        break;
                    case "/swagger-ui-bootstrap":
                    case "/swagger-ui-bootstrap/":
                    case "/swagger-ui-bootstrap/index.html":
                        indexFile = appHost.VirtualPathProvider.GetFile("/swagger-ui-bootstrap/index.html");
                        break;
                    default:
                        indexFile = null;
                        break;
                }
                if (indexFile != null)
                {
                    var html = indexFile.ReadAllText();

                    return new CustomResponseHandler((req, res) =>
                    {
                        res.ContentType = MimeTypes.Html;
                        var resourcesUrl = req.ResolveAbsoluteUrl("~/resources");
                        html = html.Replace("http://petstore.swagger.wordnik.com/api/api-docs", resourcesUrl)
                            .Replace("ApiDocs", HostContext.ServiceName)
                            .Replace("{LogoUrl}", LogoUrl);
                        return html;
                    });
                }
                return pathInfo.StartsWith("/swagger-ui") ? new StaticFileHandler() : null;
            });
        }
Esempio n. 23
0
        public void Register(IAppHost appHost)
        {
            appHost.ContentTypes.Register(MimeTypes.Wire,
                                          Serialize,
                                          Deserialize);

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/wire-format", nameof(WireFormat));
        }
Esempio n. 24
0
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService<PostmanService>(AtRestPath);

            appHost.GetPlugin<MetadataFeature>()
                   .AddPluginLink(AtRestPath.TrimStart('/'), "Postman Metadata");

            if (EnableSessionExport == null)
                EnableSessionExport = appHost.Config.DebugMode;
        }
Esempio n. 25
0
        public void Register(IAppHost appHost)
        {
            //Register the 'text/csv' content-type and serializers (format is inferred from the last part of the content-type)
            appHost.ContentTypes.Register(MimeTypes.Csv,
                                          SerializeToStream, CsvSerializer.DeserializeFromStream);

            //Add a response filter to add a 'Content-Disposition' header so browsers treat it natively as a .csv file
            appHost.GlobalResponseFilters.Add((req, res, dto) =>
            {
                if (req.ResponseContentType == MimeTypes.Csv)
                {
                    res.AddHeader(HttpHeaders.ContentDisposition, $"attachment;filename={req.OperationName}.csv");
                }
            });

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/csv-format", "CSV Format");
            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/jsv-format", "JSV Format");
        }
Esempio n. 26
0
        public void Register(IAppHost appHost)
        {
            foreach (var entry in ImplicitConventions)
            {
                var key = entry.Key.Trim('%');
                var fmt = entry.Value;
                var query = new QueryDbFieldAttribute {
                    Template = fmt
                }.Init();
                if (entry.Key.EndsWith("%"))
                {
                    StartsWithConventions[key] = query;
                }
                if (entry.Key.StartsWith("%"))
                {
                    EndsWithConventions[key] = query;
                }
            }

            appHost.GetContainer().Register <IAutoQuery>(c =>
                                                         new AutoQuery
            {
                IgnoreProperties         = IgnoreProperties,
                IllegalSqlFragmentTokens = IllegalSqlFragmentTokens,
                MaxLimit                      = MaxLimit,
                EnableUntypedQueries          = EnableUntypedQueries,
                EnableSqlFilters              = EnableRawSqlFilters,
                OrderByPrimaryKeyOnLimitQuery = OrderByPrimaryKeyOnPagedQuery,
                QueryFilters                  = QueryFilters,
                ResponseFilters               = ResponseFilters,
                StartsWithConventions         = StartsWithConventions,
                EndsWithConventions           = EndsWithConventions,
                UseNamedConnection            = UseNamedConnection,
            })
            .ReusedWithin(ReuseScope.None);

            appHost.Metadata.GetOperationAssemblies()
            .Each(x => LoadFromAssemblies.Add(x));

            ((ServiceStackHost)appHost).ServiceAssemblies.Each(x => {
                if (!LoadFromAssemblies.Contains(x))
                {
                    LoadFromAssemblies.Add(x);
                }
            });

            if (EnableAutoQueryViewer && appHost.GetPlugin <AutoQueryMetadataFeature>() == null)
            {
                appHost.LoadPlugin(new AutoQueryMetadataFeature {
                    MaxLimit = MaxLimit
                });
            }
        }
Esempio n. 27
0
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService <PostmanService>(AtRestPath);

            appHost.GetPlugin <MetadataFeature>()
            .AddPluginLink(AtRestPath.TrimStart('/'), "Postman Metadata");

            if (EnableSessionExport == null)
            {
                EnableSessionExport = appHost.Config.DebugMode;
            }
        }
        public HashSet <Type> GetRequestTypes(IAppHost host)
        {
            // registered the requestDTO type names for the lookup
            // ignores types based on
            // https://github.com/ServiceStack/ServiceStack/wiki/Add-ServiceStack-Reference#excluding-types-from-add-servicestack-reference
            var nativeTypes = host.GetPlugin <NativeTypesFeature>();

            return
                (host.Metadata.RequestTypes
                 .WithServiceDiscoveryAllowed()
                 .WithoutNativeTypes(nativeTypes)
                 .ToHashSet());
        }
        /// <summary>
        /// Registers the apphost with consul
        /// </summary>
        /// <param name="appHost"></param>
        public void Register(IAppHost appHost)
        {
            // get endpoint http://url:port/path and version
            var baseUrl    = appHost.Config.WebHostUrl.CombineWith(appHost.Config.HandlerFactoryPath);
            var dtoTypes   = GetRequestTypes(appHost);
            var customTags = appHost.GetPlugin <ConsulFeature>().Settings.GetCustomTags();

            // construct registration
            var registration = new ServiceRegistration
            {
                Name    = "api",
                Id      = $"ss-{HostContext.ServiceName}-{Guid.NewGuid()}",
                Address = baseUrl,
                Version = GetVersion(),
                Port    = GetPort(baseUrl)
            };

            // build the service tags
            var tags = new List <string> {
                $"ss-version-{registration.Version}"
            };

            tags.AddRange(dtoTypes.Select(x => x.Name));
            tags.AddRange(customTags);
            registration.Tags = tags.ToArray();

            try
            {
                // register the service and healthchecks with consul
                ConsulClient.RegisterService(registration);
                var heathChecks = CreateHealthChecks(registration);
                ConsulClient.RegisterHealthChecks(heathChecks);
                registration.HealthChecks = heathChecks;
            }
            catch (Exception e)
            {
                throw new GatewayServiceDiscoveryException($"Failed to register the service with consul agent {ConsulUris.LocalAgent}", e);
            }

            // TODO Generate warnings if dto's have [Restrict(RequestAttributes.Secure)]
            // but are being registered without an https:// baseUri

            // TODO for sorting by versioning to work, any registered version tag must be numeric
            // option 1: use ApiVersion but throw exception to stop host if it is not numeric
            // option 2: use a dedicated numeric version property which defaults to 1.0
            // option 3: use the appost's assembly version
            //var version = "v{0}".Fmt(host.Config?.ApiVersion?.Replace('.', '-'));

            // assign if self-registration was successful
            Registration = registration;
        }
 public void Register(IAppHost appHost)
 {
     if (_swaggerUiConfig == null)
     {
         _swaggerUiConfig = new SwaggerUiConfig(appHost.Config);
     }
     else
     {
         _swaggerUiConfig.HostConfig = appHost.Config;
     }
     appHost.Config.RawHttpHandlers.Add(ResolveHttpHandler);
     appHost.GetPlugin <MetadataFeature>()
     .AddPluginLink(SwaggerUiHandler.RESOURCE_PATH + "/", "Swagger UI");
 }
Esempio n. 31
0
        public static void AddToAppMetadata(this IAppHost appHost, Action <AppMetadata> fn)
        {
            var feature = appHost.GetPlugin <MetadataFeature>();

            if (feature == null)
            {
                return;
            }

            if (fn != null)
            {
                feature.AppMetadataFilters.Add(fn);
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Registers the apphost with consul
        /// </summary>
        /// <param name="appHost"></param>
        public void Register(IAppHost appHost)
        {
            Registration = new List <ServiceRegistration>();
            // get endpoint http://url:port/path and version

            string baseUrl = string.Empty;

            if (!string.IsNullOrEmpty(appHost.Config.WebHostUrl))
            {
                baseUrl = appHost.Config.WebHostUrl;
            }
            else
            {
                baseUrl = "http://" + (appHost.Config.WebHostIP + (string.IsNullOrEmpty(appHost.Config.WebHostPort) ? ":80" : ":" + appHost.Config.WebHostPort)).CombineWith(appHost.Config.ServiceStackHandlerFactoryPath);
            }

            //var dtoTypes = GetRequestTypes(appHost);
            var customSetting = appHost.GetPlugin <ConsulFeature>().Settings;
            var customTags    = customSetting.GetCustomTags();

            foreach (ServiceMetadata metadata in EndpointHost.Config.MetadataMap.Values)
            {
                //可能有多个服务
                //名称用 服务 + IP ?
                // construct registration
                string host;
                var    port         = GetPort(baseUrl, out host);
                var    registration = new ServiceRegistration
                {
                    Name    = metadata.RefinedFullServiceName,
                    Id      = $"soa-{host}/{port}--{metadata.ServiceName}",
                    Address = baseUrl,
                    Port    = port//填port
                };

                // build the service tags
                var tags = new List <string> ();
                tags.Add("N:{0}|A:[{1}]".Fmt(registration.Name, registration.Address));
                tags.AddRange(customTags);
                registration.Tags = tags.ToArray();

                // register the service and healthchecks with consul
                ConsulClient.RegisterService(registration);
                var heathChecks = CreateHealthChecks(registration, customSetting);
                ConsulClient.RegisterHealthChecks(heathChecks);
                registration.HealthChecks = heathChecks;

                Registration.Add(registration);
            }
        }
Esempio n. 33
0
        public void Register(IAppHost appHost)
        {
            var s = AuthenticateService.CurrentSessionFactory() as IWebSudoAuthSession;
            if (s == null)
            {
                throw new NotSupportedException("The IUserAuth session must also implement IWebSudoAuthSession");
            }

            appHost.GlobalRequestFilters.Add(OnRequestStart);
            appHost.GlobalResponseFilters.Add(OnRequestEnd);

            var authFeature = appHost.GetPlugin<AuthFeature>();
            authFeature.AuthEvents.Add(this);
        }
Esempio n. 34
0
        /// <summary>
        ///     Registers the <see cref="IPlugin" />
        /// </summary>
        public void Register(IAppHost appHost)
        {
            plugIn.Register(appHost);

            // Replace previous plugin link
            appHost.GetPlugin <MetadataFeature>().PluginLinks.Remove("swagger-ui/");
            string newPluginPath = "{0}/".FormatWith(directory);

            appHost.GetPlugin <MetadataFeature>().AddPluginLink(newPluginPath, "Swagger UI");
            appHost.CatchAllHandlers.Add(delegate(string httpMethod, string pathInfo, string filePath)
            {
                var supportedPaths = new[]
                {
                    "/{0}".FormatWith(directory),
                    "/{0}/".FormatWith(directory),
                    "/{0}/default.html".FormatWith(directory)
                };
                string newPath = "/{0}/index.html".FormatWith(directory);

                if (supportedPaths.Contains(pathInfo, StringComparer.OrdinalIgnoreCase))
                {
                    IVirtualFile file = appHost.VirtualPathProvider.GetFile(newPath);
                    if (file != null)
                    {
                        string html = file.ReadAllText();
                        return(new CustomResponseHandler(delegate(IRequest req, IResponse res)
                        {
                            res.ContentType = MimeTypes.Html;
                            string newValue = req.ResolveAbsoluteUrl(@"~/resources");
                            html = html.Replace("http://petstore.swagger.wordnik.com/api/api-docs", newValue);
                            return html;
                        }, null));
                    }
                }
                return(null);
            });
        }
Esempio n. 35
0
        public void Register(IAppHost appHost)
        {
            //Register this in ServiceStack with the custom formats
            appHost.ContentTypes.RegisterAsync(MimeTypes.Html, SerializeToStreamAsync, null);
            appHost.ContentTypes.RegisterAsync(MimeTypes.JsonReport, SerializeToStreamAsync, null);

            appHost.Config.DefaultContentType = MimeTypes.Html;
            appHost.Config.IgnoreFormatsInMetadata.Add(MimeTypes.Html.ToContentFormat());
            appHost.Config.IgnoreFormatsInMetadata.Add(MimeTypes.JsonReport.ToContentFormat());

            ViewEngines = appHost.ViewEngines;

            appHost.GetPlugin <MetadataFeature>()
            ?.AddLink(MetadataFeature.AvailableFeatures, "http://docs.servicestack.net/html5reportformat", "HTML5 Report Format");
        }
        public void Register(IAppHost appHost)
        {
            // HACK: not great but unsure how to improve
            // throws exception if WebHostUrl isn't set as this is how we get endpoint url:port
            if (appHost.Config?.WebHostUrl == null)
                throw new ApplicationException("appHost.Config.WebHostUrl must be set to use the Consul plugin, this is so consul will know the full external http://url:port for the service");

            // register callbacks
            appHost.AfterInitCallbacks.Add(RegisterService);
            appHost.OnDisposeCallbacks.Add(UnRegisterService);

            appHost.RegisterService<HealthCheckService>();
            appHost.RegisterService<DiscoveryService>();

            // register plugin link
            appHost.GetPlugin<MetadataFeature>()?.AddPluginLink(ConsulUris.LocalAgent.CombineWith("ui"), "Consul Agent WebUI");
        }
Esempio n. 37
0
        public void Register(IAppHost appHost)
        {
            var indexHtml = appHost.VirtualFileSources.GetFile("ss_admin/index.html").ReadAllText();

            appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
                pathInfo.StartsWith("/ss_admin")
                    ? (pathInfo == "/ss_admin/index.html" || !appHost.VirtualFileSources.FileExists(pathInfo)
                        ? new CustomActionHandler((req, res) => {
                            res.ContentType = MimeTypes.Html;
                            res.Write(indexHtml.Replace("/ss_admin", req.ResolveAbsoluteUrl("~/ss_admin")));
                        }) as IHttpHandler
                        : new StaticFileHandler(appHost.VirtualFileSources.GetFile(pathInfo)))
                    : null);

            appHost.GetPlugin<MetadataFeature>()
                .AddPluginLink("ss_admin/autoquery/", "AutoQuery Viewer");
        }
Esempio n. 38
0
        public void Register(IAppHost appHost)
        {
            if (ResourceFilterPattern != null)
                SwaggerResourcesService.resourceFilterRegex = new Regex(ResourceFilterPattern, RegexOptions.Compiled);

            SwaggerApiService.UseCamelCaseModelPropertyNames = UseCamelCaseModelPropertyNames;
            SwaggerApiService.UseLowercaseUnderscoreModelPropertyNames = UseLowercaseUnderscoreModelPropertyNames;
            SwaggerApiService.DisableAutoDtoInBodyParam = DisableAutoDtoInBodyParam;
            SwaggerApiService.ModelFilter = ModelFilter;
            SwaggerApiService.ModelPropertyFilter = ModelPropertyFilter;

            appHost.RegisterService(typeof(SwaggerResourcesService), new[] { "/resources" });
            appHost.RegisterService(typeof(SwaggerApiService), new[] { SwaggerResourcesService.RESOURCE_PATH + "/{Name*}" });

            var metadata = appHost.GetPlugin<MetadataFeature>();
            if (metadata != null)
            {
                metadata.PluginLinks["swagger-ui/"] = "Swagger UI";
            }

            appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) =>
            {
                if (pathInfo == "/swagger-ui" || pathInfo == "/swagger-ui/" || pathInfo == "/swagger-ui/default.html")
                {
                    var indexFile = appHost.VirtualPathProvider.GetFile("/swagger-ui/index.html");
                    if (indexFile != null)
                    {
                        var html = indexFile.ReadAllText();

                        return new CustomResponseHandler((req, res) =>
                        {
                            res.ContentType = MimeTypes.Html;
                            var resourcesUrl = req.ResolveAbsoluteUrl("~/resources");
                            html = html.Replace("http://petstore.swagger.wordnik.com/api/api-docs", resourcesUrl);
                            return html;
                        });
                    }
                }
                return null;
            });
        }
        public void Register(IAppHost appHost)
        {
            configValidator.ValidateAndThrow(this);

            ConfigureRequestLogger(appHost);
            appHost.RegisterService(typeof(SeqRequestLogConfigService));
            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) =>
                {
                    httpReq.UseBufferedStream = true;
                });
            }

            appHost.GetPlugin<MetadataFeature>()
                .AddDebugLink(SeqUrl, "Seq Request Logs")
                .AddPluginLink("/SeqRequestLogConfig", "Seq IRequestLogger Configuration");
        }
        public void Register(IAppHost appHost)
        {
            appHost.RegisterService<RequestLogsService>(AtRestPath);

            var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity);
            requestLogger.EnableSessionTracking = EnableSessionTracking;
            requestLogger.EnableResponseTracking = EnableResponseTracking;
            requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking;
            requestLogger.EnableErrorTracking = EnableErrorTracking;
            requestLogger.RequiredRoles = RequiredRoles;
            requestLogger.ExcludeRequestDtoTypes = ExcludeRequestDtoTypes;
            requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes;

            appHost.Register(requestLogger);

            if (EnableRequestBodyTracking)
            {
                appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) => {
                    httpReq.UseBufferedStream = EnableRequestBodyTracking;
                });
            }

            appHost.GetPlugin<MetadataFeature>()
                .AddDebugLink(AtRestPath, "Request Logs");
        }