public override void Configure(Container container) { // Force a response type of JSON. RequestFilters.Add( (IHttpRequest httpReq, IHttpResponse httpResp, object requestDto) => { var sessionId = httpReq.ResponseContentType = "text/json"; }); ResponseFilters.Add((IHttpRequest request, IHttpResponse response, object dto) => { var statusCode = dto as string; if (statusCode != null) { response.StatusCode = int.Parse(statusCode); } var dict = dto as Dictionary <string, object>; if (dict != null) { var val = dict["value"]; var json = val as JsonObject; if (json != null) { Logger.Info(JsonSerializer.SerializeToString(json)); } else { Logger.Info(val.ToString()); } } }); }
/// <summary>Override Configure method</summary> public override void Configure(Container container) { System.Configuration.Configuration rootWebConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null); JsConfig.ExcludeTypeInfo = false; JsConfig.IncludePublicFields = false; log4net.Config.XmlConfigurator.Configure(); //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method var config = new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" } //{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }//, }, DebugMode = true, //Enable StackTraces in development WebHostUrl = rootWebConfig.AppSettings.Settings["BaseUrl"].Value, WriteErrorsToResponse = false, //custom exception handling ServiceStackHandlerFactoryPath = "t2api", //WsdlServiceNamespace = "t2api", ReturnsInnerException = false }; config.AllowFileExtensions.Add("json"); config.AllowFileExtensions.Add("geojson"); config.AllowFileExtensions.Add("woff2"); base.SetConfig(config); this.ContentTypeFilters.Register("application/opensearchdescription+xml", AppHost.CustomXmlSerializer, null); ResponseFilters.Add(CustomResponseFilter); this.ServiceExceptionHandler = ExceptionHandling.ServiceExceptionHandler; }
public override void Configure(Container container) { LoadConfigEnv(); RequestFilters.Add((req, resp, requestDto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod, req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent)); }); ResponseFilters.Add((req, resp, dto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode, resp.ContentType)); }); JsConfig.DateHandler = JsonDateHandler.ISO8601; Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider() }) ); Plugins.Add(new RegistrationFeature()); Plugins.Add(new SessionFeature()); Plugins.Add(new RequestLogsFeature()); container.Register <IRedisClientsManager>(c => new PooledRedisClientManager(m_redisConnString)); container.Register <ICacheClient>(c => (ICacheClient)c.Resolve <IRedisClientsManager>() .GetCacheClient()) .ReusedWithin(Funq.ReuseScope.None); container.Register <IDbConnectionFactory>( new OrmLiteConnectionFactory(m_pgConnString, PostgreSQLDialectProvider.Instance) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info container.Register <IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(CreateQueueValidator).Assembly); container.RegisterValidators(typeof(CreateTopicValidator).Assembly); var config = new EndpointHostConfig(); if (m_debugEnabled) { config.DebugMode = true; //Show StackTraces in service responses during development config.WriteErrorsToResponse = true; config.ReturnsInnerException = true; } SetConfig(config); CreateMissingTables(container); }
public override void Configure(Container container) { RequestFilters.Add((req, resp, requestDto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod, req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent)); }); ResponseFilters.Add((req, resp, dto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode, resp.ContentType)); }); JsConfig.DateHandler = JsonDateHandler.ISO8601; Plugins.Add(new RequestLogsFeature()); ConfigureQueues(container); var config = new EndpointHostConfig(); if (m_debugEnabled) { config.DebugMode = true; config.WriteErrorsToResponse = true; config.ReturnsInnerException = true; } SetConfig(config); }
private void ConfigureNotFound() { ResponseFilters.Add((request, response, obj) => { if (obj == null) { response.StatusCode = (int)HttpStatusCode.NotFound; } }); }
public override void Configure(Container container) { RequestFilters.Add((req, resp, requestDto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod, req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent)); }); ResponseFilters.Add((req, resp, dto) => { var log = LogManager.GetLogger(GetType()); log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode, resp.ContentType)); }); JsConfig.DateHandler = JsonDateHandler.ISO8601; Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CredentialsAuthProvider() }) ); Plugins.Add(new RegistrationFeature()); Plugins.Add(new SessionFeature()); Plugins.Add(new RequestLogsFeature()); container.Register <ICacheClient> (new MemoryCacheClient()); container.Register <IDbConnectionFactory> ( new OrmLiteConnectionFactory(@"Data Source=db.sqlite;Version=3;", SqliteOrmLiteDialectProvider.Instance) { ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current) }); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info container.Register <IUserAuthRepository> (c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory> ())); Plugins.Add(new ValidationFeature()); var config = new EndpointHostConfig(); if (m_debugEnabled) { config.DebugMode = true; //Show StackTraces in service responses during development config.WriteErrorsToResponse = true; config.ReturnsInnerException = true; } SetConfig(config); }
/// <summary> /// Adds the rest handlers. /// </summary> /// <param name="services">The services.</param> public void Init(IEnumerable <IService> services) { _restServices.AddRange(services); ServiceController = CreateServiceController(); _logger.Info("Calling ServiceStack AppHost.Init"); ServiceController.Init(this); var requestFilters = _appHost.GetExports <IRequestFilter>().ToList(); foreach (var filter in requestFilters) { RequestFilters.Add(filter.Filter); } ResponseFilters.Add(new ResponseFilter(_logger).FilterResponse); }
public override void Configure(Container container) { // I add some request/response filters to set up the correct database // connection for the integration test database RequestFilters.Add((httpRequest, httpResponse, requestDto) => { var dbContext = MakeSomeDatabaseContext(); httpRequest.Items["DatabaseIntegrationTestContext"] = dbContext; }); ResponseFilters.Add((httpRequest, httpResponse, responseDto) => { var dbContext = httpRequest.Items["DatabaseIntegrationTestContext"] as DbContext; if (dbContext != null) { dbContext.Dispose(); httpRequest.Items.Remove("DatabaseIntegrationTestContext"); } }); // now include any configuration you want to share between this // and your regular AppHost, e.g. IoC setup, EndpointHostConfig, // JsConfig setup, adding Plugins, etc. SharedAppHost.Configure(container); }
/// <summary> /// Configures the specified container. /// </summary> /// <param name="container">The container.</param> public override void Configure(Container container) { JsConfig.DateHandler = JsonDateHandler.ISO8601; JsConfig.ExcludeTypeInfo = true; JsConfig.IncludeNullValues = false; SetConfig(new EndpointHostConfig { DefaultRedirectPath = DefaultRedirectPath, MapExceptionToStatusCode = { { typeof(InvalidOperationException), 422 }, { typeof(ResourceNotFoundException), 404 }, { typeof(FileNotFoundException), 404 }, { typeof(DirectoryNotFoundException), 404 } }, DebugMode = true, ServiceName = ServerName, LogFactory = LogManager.LogFactory, // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users // Custom format allows images EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat }); container.Adapter = _containerAdapter; Plugins.Add(new SwaggerFeature()); Plugins.Add(new CorsFeature()); ResponseFilters.Add(FilterResponse); }
/// <summary> /// Configures the specified container. /// </summary> /// <param name="container">The container.</param> public override void Configure(Container container) { JsConfig.DateHandler = JsonDateHandler.ISO8601; JsConfig.ExcludeTypeInfo = true; JsConfig.IncludeNullValues = false; SetConfig(new EndpointHostConfig { DefaultRedirectPath = DefaultRedirectPath, // Tell SS to bubble exceptions up to here WriteErrorsToResponse = false }); container.Adapter = new ContainerAdapter(ApplicationHost); Plugins.Add(new SwaggerFeature()); Plugins.Add(new CorsFeature()); ServiceStack.Logging.LogManager.LogFactory = new NLogFactory(); ResponseFilters.Add((req, res, dto) => { var exception = dto as Exception; if (exception != null) { _logger.ErrorException("Error processing request", exception); if (!string.IsNullOrEmpty(exception.Message)) { res.AddHeader("X-Application-Error-Code", exception.Message.Replace(Environment.NewLine, " ")); } } if (dto is CompressedResult) { // Per Google PageSpeed // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed. // The correct version of the resource is delivered based on the client request header. // This is a good choice for applications that are singly homed and depend on public proxies for user locality. res.AddHeader("Vary", "Accept-Encoding"); } var hasOptions = dto as IHasOptions; if (hasOptions != null) { // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy string contentLength; if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength)) { var length = long.Parse(contentLength); if (length > 0) { var response = (HttpListenerResponse)res.OriginalResponse; response.ContentLength64 = length; // Disable chunked encoding. Technically this is only needed when using Content-Range, but // anytime we know the content length there's no need for it response.SendChunked = false; } } } }); }
public override void Configure(Container containerFunq) { Log.Info("Configure AppHost"); new Module().Init(UnityServiceLocator.Instance); var container = UnityServiceLocator.Instance; containerFunq.Adapter = new UnityContainerAdapter(container, new Logger()); var serverSettings = container.Resolve <IServerSettings>(); Plugins.Add(new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new CustomCredentialsAuthProvider(UnityContainerExtensions.Resolve <ICommandBus>(container), UnityContainerExtensions.Resolve <IAccountDao>(container), UnityContainerExtensions.Resolve <IPasswordService>(container), UnityContainerExtensions.Resolve <IServerSettings>(container)), new CustomFacebookAuthProvider(UnityContainerExtensions.Resolve <IAccountDao>(container)), new CustomTwitterAuthProvider(UnityContainerExtensions.Resolve <IAccountDao>(container)) })); Plugins.Add(new ValidationFeature()); containerFunq.RegisterValidators(typeof(SaveFavoriteAddressValidator).Assembly); RequestFilters.Add((httpReq, httpResp, requestDto) => { var authSession = httpReq.GetSession(); if (authSession != null && !string.IsNullOrEmpty(authSession.UserAuthId)) { var account = container.Resolve <IAccountDao>().FindById(new Guid(authSession.UserAuthId)); if (account == null || account.DisabledByAdmin) { httpReq.RemoveSession(); } } }); SetConfig(new EndpointHostConfig { GlobalResponseHeaders = { { "Access-Control-Allow-Origin", "*" }, { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }, }, EnableFeatures = (serverSettings.ServerData.ShowAPIMetadata ? Feature.All : Feature.All.Remove(Feature.Metadata)) }); ContentTypeFilters.Register("text/x-csv", CsvCustomSerializer.SerializeToStream, CsvCustomSerializer.DeserializeFromStream); ResponseFilters.Add((req, res, dto) => { if (req.ResponseContentType == "text/x-csv") { res.AddHeader(HttpHeaders.ContentDisposition, string.Format("attachment;filename={0}.csv", req.OperationName)); } }); Log.Info("Configure AppHost finished"); }
public FragmentApplicationBuilderOptions AddResponseFilter(Func <HttpContext, FragmentResponseFilter> responseFilterCreator) { ResponseFilters.Add(responseFilterCreator); return(this); }