public override object HandleException(IRequestContext requestContext, T request, Exception ex)
 {
     if (isYourCondition)
     {
         ResponseStatus rs = new ResponseStatus("YourException", "your_log");
         // optionally if anybody wants custom response errors
         rs.Errors = new List <ResponseError>();
         rs.Errors.Add(new ResponseError());
         rs.Errors[0].ErrorCode = "testCode123";
         // create errorResponse with the custom responseStatus
         var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs);
         // log the error
         DtoUtils.HandleException(AppHost, request, ex);
         return(errorResponse);
     }
     else
     {
         return(base.HandleException(requestContext, request, ex));
     }
 }
Esempio n. 2
0
        public List <Child> GetFilteredChildren(int idEvent, int ageMin, int ageMax)
        {
            SendRequest(new FilterChildrenRequest(Parser.ToString(idEvent, ageMin, ageMax)));
            Response response = ReadResponse();

            if (response is ErrorResponse)
            {
                ErrorResponse e = (ErrorResponse)response;
                throw new Error(e.Message);
            }

            Child[]      listOfChildren = DtoUtils.GetFromDto(((ListOfChildrenResponse)response).Children);
            List <Child> result         = new List <Child>();

            for (int i = 0; i < listOfChildren.Length; i++)
            {
                result.Add(listOfChildren[i]);
            }
            return(result);
        }
            public override void Configure(Container container)
            {
                SetConfig(new HostConfig {
                    DebugMode = false
                });

                OnEndRequestCallbacks.Add(req => {
                    Interlocked.Increment(ref OnEndRequestCallbacksCount);
                });

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is UncatchedException || dto is UncatchedExceptionAsync)
                    {
                        throw new ArgumentException();
                    }
                });

                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlersAsync.Add(async(req, res, operationName, ex) =>
                {
                    await res.WriteAsync($"UncaughtException {ex.GetType().Name}");
                    res.EndRequest(skipHeaders: true);
                });

                this.ServiceExceptionHandlersAsync.Add(async(httpReq, request, ex) =>
                {
                    await Task.Yield();

                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
Esempio n. 4
0
        public List <Event> GetAllEvents()
        {
            SendRequest(new GetEventsRequest());
            Response r = ReadResponse();

            if (r is ErrorResponse)
            {
                ErrorResponse e = (ErrorResponse)r;
                throw new Error(e.Message);
            }
            Event[] events = DtoUtils.GetFromDto(((ListOfEventsResponse)r).Events);

            List <Event> result = new List <Event>();

            for (int i = 0; i < events.Length; i++)
            {
                result.Add(events[i]);
            }

            return(result);
        }
Esempio n. 5
0
    public override object HandleException(IRequestContext requestContext, T request, Exception ex)
    {
        if (isYourCondition)
        {
            ResponseStatus rs = new ResponseStatus("error1", "your_message");
            // optionally you can add custom response errors
            rs.Errors = new List <ResponseError>();
            rs.Errors.Add(new ResponseError());
            rs.Errors[0].ErrorCode = "more details 2";

            // create an ErrorResponse with the ResponseStatus as parameter
            var errorResponse = DtoUtils.CreateErrorResponse(request, ex, rs);
            // log the error
            Log.Error("your_message", ex);
            return(errorResponse);
        }
        else
        {
            return(base.HandleException(requestContext, request, ex));
        }
    }
Esempio n. 6
0
        public static Task RequestFilterAsync(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());
            var ruleSet   = req.Verb;

            if (validator == null || !validator.HasAsyncValidators(ruleSet))
            {
                return(TypeConstants.EmptyTask);
            }

            var validateTask = validator.ValidateAsync(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))
            {
                Request = req
            });

            return(HostContext.Async.ContinueWith(req, validateTask, t =>
            {
                var validationResult = t.Result;
                if (validationResult.IsValid)
                {
                    return TypeConstants.TrueTask;
                }

                var errorResponse = HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                if (validationFeature?.ErrorResponseFilter != null)
                {
                    errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                }

                return res.WriteToResponse(req, errorResponse);
            })
                   .ContinueWith(t =>
            {
                using (validator as IDisposable) { }
            }));
        }
        public ResponseStatus Parse(Exception exception)
        {
            var validationError = exception as ValidationError;

            if (validationError != null)
            {
                return(this.Parse(validationError));
            }

            var validationException = exception as ValidationException;

            if (validationException != null)
            {
                return(this.Parse(validationException));
            }

            var httpError = exception as IHttpError;

            return(httpError != null
                ? DtoUtils.CreateErrorResponse(httpError.ErrorCode, httpError.Message)
                : DtoUtils.CreateErrorResponse(exception.GetType().Name, exception.Message));
        }
Esempio n. 8
0
        public static void RequestFilter(IRequest req, IResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            try
            {
                var ruleSet          = req.Verb;
                var validationResult = validator.Validate(
                    new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet))
                {
                    Request = req
                });

                if (validationResult.IsValid)
                {
                    return;
                }

                var errorResponse = HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                                    ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
                {
                    errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
                }

                res.WriteToResponse(req, errorResponse);
            }
            finally
            {
                using (validator as IDisposable) {}
            }
        }
        public static async Task ResponseFilterAsync(IRequest req, IResponse res, object requestDto)
        {
            if (!(requestDto is IHasResponseStatus response))
            {
                return;
            }

            var validator = ValidatorCache.GetValidator(req, req.Dto.GetType());

            if (validator == null)
            {
                return;
            }

            var validationResult = await ValidateAsync(validator, req, req.Dto);

            if (!validationResult.IsValid)
            {
                var responseStatus = response.ResponseStatus
                                     ?? DtoUtils.CreateResponseStatus(validationResult.Errors[0].ErrorCode);
                foreach (var error in validationResult.Errors)
                {
                    var responseError = new ResponseError
                    {
                        ErrorCode = error.ErrorCode,
                        FieldName = error.PropertyName,
                        Message   = error.ErrorMessage,
                        Meta      = new Dictionary <string, string> {
                            ["Severity"] = error.Severity.ToString()
                        }
                    };
                    responseStatus.Errors.Add(responseError);
                }

                response.ResponseStatus = responseStatus;
            }
        }
Esempio n. 10
0
        public static void RequestFilter(IHttpRequest req, IHttpResponse res, object requestDto)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            var validatorWithHttpRequest = validator as IRequiresHttpRequest;

            if (validatorWithHttpRequest != null)
            {
                validatorWithHttpRequest.HttpRequest = req;
            }

            var ruleSet          = req.HttpMethod;
            var validationResult = validator.Validate(
                new ValidationContext(requestDto, null, new MultiRuleSetValidatorSelector(ruleSet)));

            if (validationResult.IsValid)
            {
                return;
            }

            var errorResponse = DtoUtils.CreateErrorResponse(
                requestDto, validationResult.ToErrorResult());

            var validationFeature = EndpointHost.GetPlugin <ValidationFeature>();

            if (validationFeature != null && validationFeature.ErrorResponseFilter != null)
            {
                errorResponse = validationFeature.ErrorResponseFilter(validationResult, errorResponse);
            }

            res.WriteToResponse(req, errorResponse);
        }
Esempio n. 11
0
        private static void SetupExceptionShielding(IAppHost appHost)
        {
            appHost.ServiceExceptionHandlers.Add((httpReq, request, exception) =>
            {
                if (IsUnexpectedException(exception))
                {
                    var error    = DtoUtils.CreateResponseStatus(exception, request, true);
                    var recorder = appHost.Resolve <IRecorder>();
                    var callerId = appHost.TryResolve <ICurrentCaller>()?.Id;
                    recorder.Crash(CrashLevel.NonCritical, exception, callerId, error.StackTrace);

                    return(DtoUtils.CreateErrorResponse(request, WrapInUnhandledException(exception)));
                }

                return(null);
            });

            appHost.UncaughtExceptionHandlers.Add((request, response, operationName, exception) =>
            {
                var recorder = appHost.Resolve <IRecorder>();
                var callerId = appHost.TryResolve <ICurrentCaller>()?.Id;
                recorder.Crash(CrashLevel.Critical, WrapInUnhandledException(exception), callerId);
                response.EndRequest(true);
            });
            public override void Configure(Container container)
            {
                JsConfig.Init(new Text.Config
                {
                    EmitCamelCaseNames = true
                });

                SetConfig(new HostConfig
                {
                    DebugMode = false,
                });

                Plugins.Add(new ProtoBufFormat());

                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
                {
                    res.WriteAsync($"UncaughtException {ex.GetType().Name}")
                    .ContinueWith(t => res.EndRequest(skipHeaders: true));
                });

                this.ServiceExceptionHandlers.Add((httpReq, request, ex) =>
                {
                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
            public override void Configure(Container container)
            {
                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
                {
                    res.Write("UncaughtException {0}".Fmt(ex.GetType().Name));
                    res.EndRequest(skipHeaders: true);
                });

                this.ServiceExceptionHandlers.Add((httpReq, request, ex) =>
                {
                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
 public override Task <object> HandleExceptionAsync(IRequest request, T requestDto, System.Exception ex)
 {
     return(DtoUtils.CreateErrorResponse(requestDto, ex).InTask());
 }
Esempio n. 15
0
        public object ExecutePath(
            string httpMethod,
            string pathInfo,
            Dictionary <string, string> queryString,
            Dictionary <string, string> formData,
            string requestBody)
        {
            var httpHandler = GetHandler(httpMethod, pathInfo);

            var contentType = (formData != null && formData.Count > 0)
                ? MimeTypes.FormUrlEncoded
                : requestBody != null ? MimeTypes.Json : null;

            var httpReq = new MockHttpRequest(
                httpHandler.RequestName, httpMethod, contentType,
                pathInfo,
                queryString.ToNameValueCollection(),
                requestBody == null ? null : new MemoryStream(Encoding.UTF8.GetBytes(requestBody)),
                formData.ToNameValueCollection()
                );

            var    request = httpHandler.CreateRequest(httpReq, httpHandler.RequestName);
            object response;

            try
            {
                response = httpHandler.GetResponse(httpReq, null, request);
            }
            catch (Exception ex)
            {
                response = DtoUtils.HandleException(AppHost, request, ex);
            }

            var httpRes = response as IHttpResult;

            if (httpRes != null)
            {
                var httpError = httpRes as IHttpError;
                if (httpError != null)
                {
                    throw new WebServiceException(httpError.Message)
                          {
                              StatusCode  = httpError.Status,
                              ResponseDto = httpError.Response
                          };
                }
                var hasResponseStatus = httpRes.Response as IHasResponseStatus;
                if (hasResponseStatus != null)
                {
                    var status = hasResponseStatus.ResponseStatus;
                    if (status != null && !status.ErrorCode.IsNullOrEmpty())
                    {
                        throw new WebServiceException(status.Message)
                              {
                                  StatusCode  = (int)HttpStatusCode.InternalServerError,
                                  ResponseDto = httpRes.Response,
                              };
                    }
                }

                return(httpRes.Response);
            }

            return(response);
        }
 public ResponseStatus Parse(ValidationError validationException)
 {
     return(DtoUtils.CreateErrorResponse(validationException.ErrorCode, validationException.Message, validationException.Violations));
 }
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var validator = ValidatorCache.GetValidator(req, requestDto.GetType());

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                try
                {
                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
Esempio n. 18
0
        public override void Configure(Container container)
        {
            JsConfig.DateHandler        = JsonDateHandler.ISO8601;
            JsConfig.EmitCamelCaseNames = true;

            Plugins.Add(new RazorFormat());

            SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                      },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE" },
                    { "Access-Control-Allow-Headers", "Content-Type"           },
                },
                DebugMode            = true,
                DefaultContentType   = ContentType.Json,
                AllowJsonpRequests   = true,
                DefaultRedirectPath  = "/stats",
                MetadataRedirectPath = "/stats",
                MetadataCustomPath   = "/stats"
            });


            //Authentication
            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                new CustomCredentialsAuthProvider()
            }
                                        )
            {
                HtmlRedirect  = "~/login.html",
                ServiceRoutes = new Dictionary <Type, string[]> {
                    { typeof(AuthService), new[] { "/auth", "/auth/{provider}" } },
                    { typeof(AssignRolesService), new[] { "/assignroles" } },
                    { typeof(UnAssignRolesService), new[] { "/unassignroles" } },
                }
            }
                        );

            //Unhandled exceptions
            //Handle Exceptions occurring in Services:
            this.ServiceExceptionHandler = (request, exception) => {
                //log your exceptions here
                Logger.LogDebug("ServiceExceptionHandler : " + exception.Message, exception.StackTrace);

                //call default exception handler or prepare your own custom response
                return(DtoUtils.HandleException(this, request, exception));
            };

            //Handle Unhandled Exceptions occurring outside of Services,
            //E.g. in Request binding or filters:
            this.ExceptionHandler = (req, res, operationName, ex) =>
            {
                Logger.LogDebug("ExceptionHandler : " + ex.Message, ex.StackTrace);
                res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                res.EndServiceStackRequest(skipHeaders: true);
            };

            /**
             * Note: since Mono by default doesn't have any trusted certificates is better to validate them in the app domain
             * than to add them manually to the deployment server
             */
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                (sender, certificate, chain, sslPolicyErrors) =>
            {
                return(true);    //Todo: fix this to actually validate the certificates
            };

            //Init
            using (var initPartners = container.Resolve <InitGatewayService>())
            {
                initPartners.Any(null);
            }

            Plugins.Add(new SwaggerFeature());
        }
        public override void Configure(Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            JsConfig.EmitCamelCaseNames          = true;
            JsConfig.ThrowOnDeserializationError = true;
            JsConfig.DateHandler          = JsonDateHandler.ISO8601;
            JsConfig <Guid> .SerializeFn  = guid => guid.ToString("D");
            JsConfig <Guid?> .SerializeFn = nullableGuid => nullableGuid.HasValue ? nullableGuid.Value.ToString("D") : string.Empty;

            Plugins.Add(new CorsFeature(ConfigurationManager.AppSettings["webSiteDomain"], "GET, POST, PUT, DELETE, OPTIONS", "Content-Type"));

            //Handles Request and closes Response after emitting global HTTP Headers
            var emitGlobalHeadersHandler = new CustomActionHandler(
                (httpReq, httpRes) => httpRes.EndRequest());

            SetConfig(new EndpointHostConfig
            {
                RawHttpHandlers = { httpReq =>
                                    httpReq.HttpMethod == HttpMethods.Options
                                ? emitGlobalHeadersHandler
                                : null }

#if !DEBUG
                , DebugMode = false   // Remove stacktrace inside the response
#endif
            });

            container.Register(c => new Database("localDB")).ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <Repository <ErrorLog> >().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <LessonRepository>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <UserRepository>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <StudentLessonAnswerRepository>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <GradeRepository>().ReusedWithin(ReuseScope.Request);

            ServiceExceptionHandler = (req, request, exception) =>
            {
                var errorLog = new ErrorLog
                {
                    Application = "MetacognitiveTutor.Api",
                    Message     = exception.Message,
                    StackTrace  = exception.StackTrace
                };
                container.Resolve <Repository <ErrorLog> >().Add(errorLog);

                return(DtoUtils.CreateErrorResponse(request, exception, new ResponseStatus(HttpStatusCode.InternalServerError.ToString())));
            };

            //Handle Unhandled Exceptions occurring outside of Services
            //E.g. Exceptions during Request binding or in filters:
            ExceptionHandler = (req, res, operationName, ex) =>
            {
                var errorLog = new ErrorLog
                {
                    Application = "MetacognitiveTutor.Api",
                    Message     = ex.Message,
                    StackTrace  = ex.StackTrace
                };
                container.Resolve <Repository <ErrorLog> >().Add(errorLog);

                res.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                res.EndRequest(skipHeaders: true);
            };

            //Enable Authentication
            //ConfigureAuth(container);
        }
Esempio n. 20
0
        public void SerializeToStream(IRequest request, object response, IResponse httpRes)
        {
            var httpResult = request.GetItem("HttpResult") as IHttpResult;

            if (httpResult != null && httpResult.Headers.ContainsKey(HttpHeaders.Location) &&
                httpResult.StatusCode != System.Net.HttpStatusCode.Created)
            {
                return;
            }

            try
            {
                if (httpRes.StatusCode >= 400)
                {
                    var responseStatus = response.GetResponseStatus();
                    request.Items[ErrorStatusKey] = responseStatus;
                }

                if (AppHost.ViewEngines.Any(x => x.ProcessRequest(request, httpRes, response)))
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                if (httpRes.StatusCode < 400)
                {
                    throw;
                }

                //If there was an exception trying to render a Error with a View,
                //It can't handle errors so just write it out here.
                response = DtoUtils.CreateErrorResponse(request.Dto, ex);
            }

            if (request.ResponseContentType != MimeTypes.Html &&
                request.ResponseContentType != MimeTypes.JsonReport)
            {
                return;
            }

            var dto  = response.GetDto();
            var html = dto as string;

            if (html == null)
            {
                // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
                var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
                json = json.Replace("<", "&lt;").Replace(">", "&gt;");

                var url = request.AbsoluteUri
                          .Replace("format=html", "")
                          .Replace("format=shtm", "")
                          .TrimEnd('?', '&');

                url += url.Contains("?") ? "&" : "?";

                var now         = DateTime.UtcNow;
                var requestName = request.OperationName ?? dto.GetType().GetOperationName();
                html = GetHtml(request, requestName)
                       .Replace("${Dto}", json)
                       .Replace("${Title}", string.Format(@"{0} - {1}", requestName, now))
                       .Replace("${MvcIncludes}", ServiceStack.MiniProfiler.Profiler.RenderIncludes().ToString())
                       .Replace("${Header}", string.Format(@"Información de <i>{0}</i> generada por <a href=""https://servicestack.net"">ServiceStack</a>  a las <b>{1}</b>", requestName, now))
                       .Replace("${Humanize}", true.ToString().ToLower())
                       .Replace("${ServiceUrl}", url);
            }

            var utf8Bytes = html.ToUtf8Bytes();

            httpRes.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
        }
Esempio n. 21
0
 /// <summary>
 /// 处理在服务内部抛出的异常
 /// </summary>
 /// <param name="httpRequest"></param>
 /// <param name="request"></param>
 /// <param name="exception"></param>
 /// <returns></returns>
 public object OnServiceExceptionHandler(
     IHttpRequest httpRequest, object request, System.Exception exception)
 {
     return(DtoUtils.HandleException(_appHost, request, exception));
 }
Esempio n. 22
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            // overrides to default ServiceStack configuration
            SetConfig(new HostConfig
            {
                EnableFeatures        = Feature.All,
                DefaultContentType    = "application/json",
                DebugMode             = true,       // show stack traces
                WriteErrorsToResponse = true,
                AdminAuthSecret       = "A0verrid3" // TODO: drop this in Production
            });

            Plugins.Add(new CorsFeature(
                            allowedOrigins: "*",
                            allowedHeaders: "Content-Type, Authorization",
                            allowCredentials: true
                            ));

            Plugins.Add(new RequestLogsFeature
            {
            });

            Plugins.Add(new SwaggerFeature
            {
                DisableAutoDtoInBodyParam = false,
            });

            // return dates like this: 2012-08-21T11:02:32.0449348-04:00
            ServiceStack.Text.JsConfig.DateHandler = ServiceStack.Text.DateHandler.ISO8601;

            // make sure default connection profile exists
            var custData = System.Configuration.ConfigurationManager.ConnectionStrings["dbCustData"].ConnectionString;
            var data     = System.Configuration.ConfigurationManager.ConnectionStrings["dbData"].ConnectionString;

            // TODO: setup correct db... We use SQL Server
            var cp = "Data Source=localhost;Initial Catalog=AuthDb;User ID=sa;Password=123;Connect Timeout=3600";


            //Register IOC dependencies
            container.Register <DbContext>(ctx => new DbContext(cp)).ReusedWithin(ReuseScope.Request);

            // handle exceptions in services
            this.ServiceExceptionHandlers.Add((httpReq, requestDto, ex) =>
            {
                return(DtoUtils.CreateErrorResponse(requestDto, ex));
            });

            // handle exceptions not in services
            this.UncaughtExceptionHandlers.Add((httpReq, httpResp, operationName, ex) =>
            {
                // TODO: Figure out what changed between ServiceStack -Version 4.0.33 -> 4.0.62 as this throws an error as HttpResponse has already been submitted
                //httpResp.Write("Error: {0}: {1}".Fmt(ex.GetType().Name, ex.Message));
                httpResp.EndRequest(skipHeaders: true);

                // FUTURE: perhaps save errors to db
            });

            this.GlobalRequestFilters.Add((req, res, dto) =>
            {
                Stopwatch sw = new Stopwatch();
                sw.Start();
                req.Items.Add("StopWatch", sw);
            });

            this.GlobalResponseFilters.Add((req, res, dto) =>
            {
                if (req.Items.ContainsKey("StopWatch"))
                {
                    var sw = req.Items["StopWatch"] as Stopwatch;
                    sw.Stop();
                }
                ;
            });

            /* TODO: determine which db to house auth info in
             * for now, dump into CustData* (NA as default)
             */
            ConfigureAuth(container, cp);
        }
Esempio n. 23
0
        public object ExecutePath(
            string httpMethod,
            string pathInfo,
            Dictionary <string, string> queryString,
            Dictionary <string, string> formData,
            string requestBody)
        {
            var contentType = (formData != null && formData.Count > 0)
                ? MimeTypes.FormUrlEncoded
                : requestBody != null ? MimeTypes.Json : null;

            var httpReq = new MockHttpRequest(
                nameof(MockHttpRequest),
                httpMethod,
                contentType,
                pathInfo,
                queryString.ToNameValueCollection(),
                requestBody == null ? null : Encoding.UTF8.GetBytes(requestBody).InMemoryStream(),
                formData.ToNameValueCollection()
                );

            var httpHandler = (IRequestHttpHandler)GetHandler(httpReq);

            httpReq.OperationName = httpHandler.RequestName;

            var    request = httpHandler.CreateRequestAsync(httpReq, httpHandler.RequestName).Result;
            object response;

            try
            {
                response = httpHandler.GetResponseAsync(httpReq, request).Result;
            }
            catch (Exception ex)
            {
                response = DtoUtils.CreateErrorResponse(request, ex);
            }

            if (response is IHttpResult httpRes)
            {
                if (httpRes is IHttpError httpError)
                {
                    throw new WebServiceException(httpError.Message)
                          {
                              StatusCode  = httpError.Status,
                              ResponseDto = httpError.Response
                          };
                }
                var hasResponseStatus = httpRes.Response as IHasResponseStatus;
                var status            = hasResponseStatus?.ResponseStatus;
                if (status != null && !status.ErrorCode.IsNullOrEmpty())
                {
                    throw new WebServiceException(status.Message)
                          {
                              StatusCode  = (int)HttpStatusCode.InternalServerError,
                              ResponseDto = httpRes.Response,
                          };
                }

                return(httpRes.Response);
            }

            return(response);
        }
 public ResponseStatus Parse(ValidationErrorResult validationResult)
 {
     return(validationResult.IsValid
         ? DtoUtils.CreateSuccessResponse(validationResult.SuccessMessage)
         : DtoUtils.CreateErrorResponse(validationResult.ErrorCode, validationResult.ErrorMessage, validationResult.Errors));
 }
Esempio n. 25
0
        public async Task SerializeToStreamAsync(IRequest req, object response, Stream outputStream)
        {
            var res = req.Response;

            if (req.GetItem("HttpResult") is IHttpResult httpResult && httpResult.Headers.ContainsKey(HttpHeaders.Location) &&
                httpResult.StatusCode != System.Net.HttpStatusCode.Created)
            {
                return;
            }

            try
            {
                if (res.StatusCode >= 400)
                {
                    var responseStatus = response.GetResponseStatus();
                    req.Items[ErrorStatusKey] = responseStatus;
                }

                if (response is CompressedResult)
                {
                    if (res.Dto != null)
                    {
                        response = res.Dto;
                    }
                    else
                    {
                        throw new ArgumentException("Cannot use Cached Result as ViewModel");
                    }
                }

                foreach (var viewEngine in ViewEngines)
                {
                    var handled = await viewEngine.ProcessRequestAsync(req, response, outputStream);

                    if (handled)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                if (res.StatusCode < 400)
                {
                    throw;
                }

                //If there was an exception trying to render a Error with a View,
                //It can't handle errors so just write it out here.
                response = DtoUtils.CreateErrorResponse(req.Dto, ex);
            }

            //Handle Exceptions returning string
            if (req.ResponseContentType == MimeTypes.PlainText)
            {
                req.ResponseContentType = MimeTypes.Html;
                res.ContentType         = MimeTypes.Html;
            }

            if (req.ResponseContentType != MimeTypes.Html && req.ResponseContentType != MimeTypes.JsonReport)
            {
                return;
            }

            var dto = response.GetDto();

            if (!(dto is string html))
            {
                // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
                var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
                json = json.Replace("<", "&lt;").Replace(">", "&gt;");

                var url       = req.ResolveAbsoluteUrl();
                var index     = url.IndexOf("?");
                var formatUrl = index != -1 ? url.Substring(0, index + 1) : url + "?";
                foreach (var key in req.QueryString.AllKeys)
                {
                    if (key == Keywords.Format)
                    {
                        continue;
                    }

                    formatUrl += (key.IsNullOrEmpty() ? "" : key + "=") + req.QueryString[key] + "&";
                }

                var now         = DateTime.Now;
                var requestName = req.OperationName ?? dto.GetType().GetOperationName();

                html = HtmlTemplates.GetHtmlFormatTemplate()
                       .Replace("${Dto}", json)
                       .Replace("${Title}", string.Format(TitleFormat, requestName, now))
                       .Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes()?.ToString())
                       .Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
                       .Replace("${ServiceUrl}", req.AbsoluteUri)
                       .Replace("${FormatUrl}", formatUrl)
                       .Replace("${Humanize}", Humanize.ToString().ToLower());
            }

            var utf8Bytes = html.ToUtf8Bytes();
            await outputStream.WriteAsync(utf8Bytes, 0, utf8Bytes.Length);
        }
Esempio n. 26
0
 public override object HandleException(IRequest request, T requestDto, System.Exception ex)
 {
     return(DtoUtils.CreateErrorResponse(requestDto, ex));
 }
Esempio n. 27
0
        private static async Task RequestFilterAsync(IRequest req, IResponse res, object requestDto,
                                                     bool treatInfoAndWarningsAsErrors)
        {
            var requestType = requestDto.GetType();
            await Validators.AssertTypeValidatorsAsync(req, requestDto, requestType);

            var validator = ValidatorCache.GetValidator(req, requestType);

            if (validator == null)
            {
                return;
            }

            using (validator as IDisposable)
            {
                if (validator is IHasTypeValidators hasTypeValidators && hasTypeValidators.TypeValidators.Count > 0)
                {
                    foreach (var scriptValidator in hasTypeValidators.TypeValidators)
                    {
                        await scriptValidator.ThrowIfNotValidAsync(requestDto, req);
                    }
                }

                try
                {
                    if (req.Verb == HttpMethods.Patch)
                    {
                        // Ignore property rules for AutoCrud Patch operations with default values that aren't reset (which are ignored)
                        if (validator is IServiceStackValidator ssValidator && requestDto is ICrud && requestType.IsOrHasGenericInterfaceTypeOf(typeof(IPatchDb <>)))
                        {
                            var typeProperties         = TypeProperties.Get(requestType);
                            var propsWithDefaultValues = new HashSet <string>();
                            var resetFields            = GetResetFields(req.GetParam(Keywords.reset))?.ToSet(StringComparer.OrdinalIgnoreCase)
                                                         ?? TypeConstants <string> .EmptyHashSet;

                            foreach (var entry in typeProperties.PropertyMap)
                            {
                                if (entry.Value.PublicGetter == null || resetFields.Contains(entry.Key))
                                {
                                    continue;
                                }
                                var defaultValue = entry.Value.PropertyInfo.PropertyType.GetDefaultValue();
                                var propValue    = entry.Value.PublicGetter(requestDto);
                                if (propValue == null || propValue.Equals(defaultValue))
                                {
                                    propsWithDefaultValues.Add(entry.Key);
                                }
                            }
                            if (propsWithDefaultValues.Count > 0)
                            {
                                ssValidator.RemovePropertyRules(rule => propsWithDefaultValues.Contains(rule.PropertyName));
                            }
                        }
                    }

                    var validationResult = await validator.ValidateAsync(req, requestDto);

                    if (treatInfoAndWarningsAsErrors && validationResult.IsValid)
                    {
                        return;
                    }

                    if (!treatInfoAndWarningsAsErrors &&
                        (validationResult.IsValid || validationResult.Errors.All(v => v.Severity != Severity.Error)))
                    {
                        return;
                    }

                    var errorResponse =
                        await HostContext.RaiseServiceException(req, requestDto, validationResult.ToException())
                        ?? DtoUtils.CreateErrorResponse(requestDto, validationResult.ToErrorResult());

                    var autoBatchIndex = req.GetItem(Keywords.AutoBatchIndex)?.ToString();
                    if (autoBatchIndex != null)
                    {
                        var responseStatus = errorResponse.GetResponseStatus();
                        if (responseStatus != null)
                        {
                            if (responseStatus.Meta == null)
                            {
                                responseStatus.Meta = new Dictionary <string, string>();
                            }
                            responseStatus.Meta[Keywords.AutoBatchIndex] = autoBatchIndex;
                        }
                    }

                    var validationFeature = HostContext.GetPlugin <ValidationFeature>();
                    if (validationFeature?.ErrorResponseFilter != null)
                    {
                        errorResponse = validationFeature.ErrorResponseFilter(req, validationResult, errorResponse);
                    }

                    await res.WriteToResponse(req, errorResponse);
                }
                catch (Exception ex)
                {
                    var validationEx = ex.UnwrapIfSingleException();

                    var errorResponse = await HostContext.RaiseServiceException(req, requestDto, validationEx)
                                        ?? DtoUtils.CreateErrorResponse(requestDto, validationEx);

                    await res.WriteToResponse(req, errorResponse);
                }
            }
        }
Esempio n. 28
0
        public void SerializeToStream(IRequest req, object response, IResponse res)
        {
            var httpResult = req.GetItem("HttpResult") as IHttpResult;

            if (httpResult != null && httpResult.Headers.ContainsKey(HttpHeaders.Location) &&
                httpResult.StatusCode != System.Net.HttpStatusCode.Created)
            {
                return;
            }

            try
            {
                if (res.StatusCode >= 400)
                {
                    var responseStatus = response.GetResponseStatus();
                    req.Items[ErrorStatusKey] = responseStatus;
                }

                if (response is CompressedResult)
                {
                    if (res.Dto != null)
                    {
                        response = res.Dto;
                    }
                    else
                    {
                        throw new ArgumentException("Cannot use Cached Result as ViewModel");
                    }
                }

                if (AppHost.ViewEngines.Any(x => x.ProcessRequest(req, res, response)))
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                if (res.StatusCode < 400)
                {
                    throw;
                }

                //If there was an exception trying to render a Error with a View,
                //It can't handle errors so just write it out here.
                response = DtoUtils.CreateErrorResponse(req.Dto, ex);
            }

            //Handle Exceptions returning string
            if (req.ResponseContentType == MimeTypes.PlainText)
            {
                req.ResponseContentType = MimeTypes.Html;
                res.ContentType         = MimeTypes.Html;
            }

            if (req.ResponseContentType != MimeTypes.Html &&
                req.ResponseContentType != MimeTypes.JsonReport)
            {
                return;
            }

            var dto  = response.GetDto();
            var html = dto as string;

            if (html == null)
            {
                // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
                var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
                json = json.Replace("<", "&lt;").Replace(">", "&gt;");

                var url = req.AbsoluteUri
                          .Replace("format=html", "")
                          .Replace("format=shtm", "")
                          .TrimEnd('?', '&');

                url += url.Contains("?") ? "&" : "?";

                var now         = DateTime.UtcNow;
                var requestName = req.OperationName ?? dto.GetType().GetOperationName();

                html = HtmlTemplates.GetHtmlFormatTemplate()
                       .Replace("${Dto}", json)
                       .Replace("${Title}", string.Format(TitleFormat, requestName, now))
                       .Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes().ToString())
                       .Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
                       .Replace("${ServiceUrl}", url)
                       .Replace("${Humanize}", Humanize.ToString().ToLower());
            }

            var utf8Bytes = html.ToUtf8Bytes();

            res.OutputStream.Write(utf8Bytes, 0, utf8Bytes.Length);
        }
 public override object HandleException(IRequestContext requestContext, T request, System.Exception ex)
 {
     return(DtoUtils.HandleException(new BasicResolver(), request, ex));
 }
Esempio n. 30
0
        public async Task SerializeToStreamAsync(IRequest req, object response, Stream outputStream)
        {
            var res = req.Response;

            if (req.GetItem("HttpResult") is IHttpResult httpResult && httpResult.Headers.ContainsKey(HttpHeaders.Location) &&
                httpResult.StatusCode != System.Net.HttpStatusCode.Created)
            {
                return;
            }

            try
            {
                if (res.StatusCode >= 400)
                {
                    var responseStatus = response.GetResponseStatus();
                    req.Items[Keywords.ErrorStatus] = responseStatus;
                }

                if (response is CompressedResult)
                {
                    if (res.Dto != null)
                    {
                        response = res.Dto;
                    }
                    else
                    {
                        throw new ArgumentException("Cannot use Cached Result as ViewModel");
                    }
                }

                foreach (var viewEngine in AppHost.ViewEngines)
                {
                    var handled = await viewEngine.ProcessRequestAsync(req, response, outputStream);

                    if (handled)
                    {
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                if (res.StatusCode < 400)
                {
                    throw;
                }

                //If there was an exception trying to render a Error with a View,
                //It can't handle errors so just write it out here.
                response = DtoUtils.CreateErrorResponse(req.Dto, ex);
            }

            //Handle Exceptions returning string
            if (req.ResponseContentType == MimeTypes.PlainText)
            {
                req.ResponseContentType = MimeTypes.Html;
                res.ContentType         = MimeTypes.Html;
            }

            if (req.ResponseContentType != MimeTypes.Html && req.ResponseContentType != MimeTypes.JsonReport)
            {
                return;
            }

            var dto = response.GetDto();

            if (!(dto is string html))
            {
                // Serialize then escape any potential script tags to avoid XSS when displaying as HTML
                var json = JsonDataContractSerializer.Instance.SerializeToString(dto) ?? "null";
                json = json.HtmlEncodeLite();

                var url = req.ResolveAbsoluteUrl()
                          .Replace("format=html", "")
                          .Replace("format=shtm", "")
                          .TrimEnd('?', '&')
                          .HtmlEncode();

                url += url.Contains("?") ? "&" : "?";

                var now         = DateTime.UtcNow;
                var requestName = req.OperationName ?? dto.GetType().GetOperationName();

                html = (ResolveTemplate?.Invoke(req) ?? Templates.HtmlTemplates.GetHtmlFormatTemplate())
                       .Replace("${Dto}", json)
                       .Replace("${BaseUrl}", req.GetBaseUrl().TrimEnd('/'))
                       .Replace("${Title}", string.Format(TitleFormat, requestName, now))
                       .Replace("${MvcIncludes}", MiniProfiler.Profiler.RenderIncludes().ToString())
                       .Replace("${Header}", string.Format(HtmlTitleFormat, requestName, now))
                       .Replace("${ServiceUrl}", url)
                       .Replace("${Humanize}", Humanize.ToString().ToLower())
                       .Replace("${AuthRedirect}", req.ResolveAbsoluteUrl(AppHost.GetPlugin <AuthFeature>()?.HtmlRedirect))
                       .Replace("${AllowOrigins}", AppHost.GetPlugin <CorsFeature>()?.AllowOriginWhitelist?.Join(";"));
            }

            await((ServiceStackHost)AppHost).WriteAutoHtmlResponseAsync(req, response, html, outputStream);
        }