public override void Configure(Container container) { // Global Configurations SetConfig(new HostConfig { DefaultContentType = MimeTypes.Json, EnableFeatures = Feature.Json, PreferredContentTypes = new List <string> { MimeTypes.Json }, MapExceptionToStatusCode = { { typeof(InabilityToProcessPayloadException), (int)HttpStatusCode.BadRequest }, } }); // Exception Handlers ServiceExceptionHandlers.Add((httpReq, request, exception) => { var message = exception.Message; Log.Error(message); Log.Error(exception.GetResponseBody()); Log.Info(httpReq.AbsoluteUri); return(exception is DeclinePaymentException ? new HttpResult( ProcessDto.GetErrorResponse(httpReq.AbsoluteUri, message, ((DeclinePaymentException)exception).ErrorCode), HttpStatusCode.OK) : new HttpResult(null, HttpStatusCode.BadRequest)); }); UncaughtExceptionHandlers.Add((req, res, operationName, ex) => { Log.Error(ex.GetResponseBody()); res.StatusCode = ex is SerializationException ? (int)HttpStatusCode.BadRequest : (int)HttpStatusCode.InternalServerError; res.EndRequest(true); }); // Global Filters PreRequestFilters.Add((req, res) => { Log.Info($"{HTTP_HEADER.HOST} : {req.UserHostAddress}"); Log.Info($"{HTTP_HEADER.USER_AGENT} : {req.UserAgent}"); Log.Info($"{HTTP_HEADER.CONTENT_LENGTH} : {req.ContentLength}"); Log.Info($"{HTTP_HEADER.CONTENT_TYPE} : {req.ContentType}"); Log.Info($"{HTTP_HEADER.ACCEPT} : {req.AcceptTypes}"); Simulate500Error.CallMqServer(); }); // Validations Plugins.Add(new ValidationFeature()); container.RegisterValidators(typeof(MerchantPaymentValidator).Assembly, typeof(MerchantPaymentAdviceValidator).Assembly, typeof(CashInValidator).Assembly, typeof(CashInAdviceValidator).Assembly, typeof(CashOutValidator).Assembly, typeof(CashOutAdviceValidator).Assembly); // IoC container.RegisterAutoWiredAs <AppSettings, IAppSettings>(); }
public override void Configure(Container container) { ServiceExceptionHandlers.Add((req, dto, ex) => { ServiceEx = ex; return(null); }); UncaughtExceptionHandlers.Add((req, res, op, ex) => { UnHandledEx = ex; }); }
public override void Configure(Container container) { ConsulSettings consulSettings = new ConsulSettings(settings => { settings.ConsulAgentUrl = "http://192.168.200.235:8500"; settings.IncludeDefaultServiceHealth = false; settings.SetDefaultGateway(baseUri => new JsonServiceClient(baseUri) { UserName = "******" }); settings.AddTags("urlprefix-/NetCoreApi.ServiceStack"); //settings.AddServiceCheck(host => //{ // return new HealthCheck(ServiceHealth.Ok, "working normally"); //}, //// default check once per minute //intervalInSeconds: 60, //// deregisters the service if health is critical after x minutes, null = disabled by default //deregisterIfCriticalAfterInMinutes: 30 //); }); var appHost = new HostConfig { // 禁用Metadata Soap11 Soap12页面 EnableFeatures = Feature.All.Remove(Feature.Metadata | Feature.Soap11 | Feature.Soap12), // 修改默认的metadata页面未swagger-ui页面 DefaultRedirectPath = "/swagger-ui/", // 禁用调试模式 DebugMode = true, // the url:port that other services will use to access this one //WebHostUrl = "http://192.168.20.133:5123", // optional //ApiVersion = "1.0", HandlerFactoryPath = "/" }; SetConfig(appHost); Plugins.Add(new ConsulFeature(consulSettings)); // 启用swagger插件 Plugins.Add(new SwaggerFeature()); // 未捕获的异常在此处统一处理 UncaughtExceptionHandlers.Add(UncaughtExceptionHandlersDel); }
public override void Configure(Container container) { Plugins.Add(new ServerEventsFeature { OnConnect = this.OnConnect, OnCreated = this.OnCreated, OnSubscribe = this.OnSubscribe, OnPublish = this.OnPublish, HeartbeatInterval = TimeSpan.FromSeconds(10), IdleTimeout = TimeSpan.FromMinutes(20), LimitToAuthenticatedUsers = false, NotifyChannelOfSubscriptions = false }); Plugins.Add(new BasicAuthFeature { HtmlRedirect = "~/login" }); SetConfig(new HostConfig { AllowSessionIdsInHttpParams = true, DebugMode = false, EnableFeatures = Feature.All.Remove(Feature.Metadata), HandlerFactoryPath = "api" }); Container.Register(c => new SseService(c.Resolve <IServerEvents>()) ); Container.Register <IRedisClientsManager>(c => new RedisManagerPool("localhost:6379") ); Container.Register <IServerEvents>(c => new RedisServerEvents(c.Resolve <IRedisClientsManager>()) ); Container.Resolve <IServerEvents>().Start(); ServiceExceptionHandlers.Add(HandleException); UncaughtExceptionHandlers.Add(HandleUnhandledException); }
public override void Configure(Container container) { // 启用swagger插件 Plugins.Add(new SwaggerFeature()); var appHost = new HostConfig { // 禁用Metadata Soap11 Soap12页面 EnableFeatures = Feature.All.Remove(Feature.Metadata | Feature.Soap11 | Feature.Soap12), // 修改默认的metadata页面未swagger-ui页面 DefaultRedirectPath = "/swagger-ui/", // 禁用调试模式 DebugMode = true, }; SetConfig(appHost); // 未捕获的异常在此处统一处理 UncaughtExceptionHandlers.Add(UncaughtExceptionHandlersDel); }
protected internal virtual ExecutorService CreateParallelExecutor() { return(Executors.NewCachedThreadPool(new ThreadFactoryBuilder().SetDaemon(true).SetNameFormat ("Logger channel (from parallel executor) to " + addr).SetUncaughtExceptionHandler (UncaughtExceptionHandlers.SystemExit()).Build())); }
protected internal virtual ExecutorService CreateSingleThreadExecutor() { return(Executors.NewSingleThreadExecutor(new ThreadFactoryBuilder().SetDaemon(true ).SetNameFormat("Logger channel (from single-thread executor) to " + addr).SetUncaughtExceptionHandler (UncaughtExceptionHandlers.SystemExit()).Build())); }
// Configure your AppHost with the necessary configuration and dependencies your App needs public override void Configure(Container container) { Plugins.Add(new PostmanFeature()); Plugins.Add(new OpenApiFeature()); SetConfig(new HostConfig { DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false), #if DEBUG AdminAuthSecret = "adm1nSecret", // Enable Admin Access with ?authsecret=adm1nSecret #endif }); container.Register <IList <GroupModel> >(new List <GroupModel>()); GlobalRequestFilters.Add((req, resp, reqDto) => { req.Items.Add("BeginTimestamp", DateTime.Now); }); GlobalResponseFilters.Add((req, resp, respDto) => { Console.WriteLine(); Console.WriteLine(); Console.WriteLine($"**************** {nameof(GlobalResponseFilters)} ****************"); //Console.WriteLine($"***** req: {req.ToSafeJson()}"); Console.WriteLine(); var beginTimestamp = req.Items["BeginTimestamp"]; var endTimestamp = DateTime.Now; Console.WriteLine($"=====> Request at [{beginTimestamp}]"); if (req.IsAuthenticated()) { var session = req.SessionAs <CustomUserSession>(); var authRepo = container.Resolve <IAuthRepository>(); var manageRole = authRepo as IManageRoles; var roles = manageRole.GetRoles(session.UserAuthId); Console.WriteLine($" Username: {session.UserName}, Roles: {roles.ToSafeJson()}"); } Console.WriteLine($" {req.Verb}, {req.OperationName}, {req.Dto.ToSafeJson()}"); Console.WriteLine(); Console.WriteLine($"<===== Response at [{endTimestamp}]"); Console.WriteLine($" Type: {respDto.GetType().Name}"); // Console.WriteLine($"***** resp: {resp.ToSafeJson()}"); // Console.WriteLine(); if (respDto is HttpError) { var error = respDto as HttpError; var respStatus = error.ResponseStatus; Console.WriteLine($" Status: {error.Status}, {error.StatusCode}, {respStatus.ErrorCode}, {respStatus.Message}"); Console.WriteLine(); } else { object success = respDto is HttpResult ? (respDto as HttpResult).Response : respDto; Console.WriteLine($" respDto: {success.ToSafeJson()}"); Console.WriteLine(); } }); //Handle Exceptions occurring in Services: // ServiceExceptionHandlers.Add((httpReq, request, exception) => { //log your exceptions here... return(null); //continue with default Error Handling //or return your own custom response //return DtoUtils.CreateErrorResponse(request, exception); }); //Handle Unhandled Exceptions occurring outside of Services //E.g. Exceptions during Request binding or in filters: // UncaughtExceptionHandlers.Add((req, res, operationName, ex) => { res.Write($"Error: {ex.GetType().Name}: {ex.Message}"); res.EndRequest(skipHeaders: true); }); container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)); container.Register <IAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()) { UseDistinctRoleTables = true, }); container.Resolve <IAuthRepository>().InitSchema(); // // TODO: Replace OAuth App settings in: appsettings.Development.json Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] { // new NetCoreIdentityAuthProvider(AppSettings) { // Adapter to enable ServiceStack Auth in MVC // AdminRoles = { "Manager" }, // Automatically Assign additional roles to Admin Users // }, new BasicAuthProvider(), //Allow Sign-ins with HTTP Basic Auth new CredentialsAuthProvider(AppSettings), // Sign In with Username / Password credentials // new FacebookAuthProvider(AppSettings), /* Create Facebook App at: https://developers.facebook.com/apps */ // new TwitterAuthProvider(AppSettings), /* Create Twitter App at: https://dev.twitter.com/apps */ // new GoogleAuthProvider(AppSettings), /* Create App https://console.developers.google.com/apis/credentials */ // new MicrosoftGraphAuthProvider(AppSettings), /* Create App https://apps.dev.microsoft.com */ }) { IncludeRegistrationService = true, IncludeAssignRoleServices = false, }); AddSeedUsers((IUserAuthRepository)container.Resolve <IAuthRepository>()); }