public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        Argument.CheckIfNull(actionExecutedContext, "actionExecutedContext");

            RaygunLogger logger = new RaygunLogger(new ConnectVersion());
            logger.Log("Web API Error", actionExecutedContext.Exception);
            base.OnException(actionExecutedContext);
    }
        private static Task<HttpResponseMessage> Handler403(
            HttpActionExecutedContext context,
            CancellationToken cancellationToken)
        {
            if (context.Exception is SecurityException)
            {
                return Task.FromResult(
                    context.Request.CreateErrorResponse(HttpStatusCode.Forbidden, context.Exception));
            }

            return Task.FromResult<HttpResponseMessage>(null);
        }
Esempio n. 3
0
 /// <summary>
 /// Occurs after the action method is invoked.
 /// </summary>
 /// <param name="actionExecutedContext">The action executed context.</param>
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     if (seconds > 0)
     {
         actionExecutedContext.Response.Headers.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue()
         {
             MaxAge = TimeSpan.FromSeconds(seconds)
         };
     }
     else
     {
         base.OnActionExecuted(actionExecutedContext);
     }
 }
    public override void OnException(HttpActionExecutedContext actionExecutedContext)
    {
        Argument.CheckIfNull(actionExecutedContext, "actionExecutedContext");

            if (actionExecutedContext.Exception.GetType() == typeof(ConcurrencyException))
            {
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Conflict)
                {
                    Content = new StringContent(actionExecutedContext.Exception.ToString())
                };

                actionExecutedContext.Response = response;
            }
            base.OnException(actionExecutedContext);
    }
        /// <summary>
        /// The callback to execute when exception occurs.
        /// </summary>
        /// <param name="actionExecutedContext">The context where the action is executed.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>The task object that represents the callback execution.</returns>
        public override async Task OnExceptionAsync(
            HttpActionExecutedContext actionExecutedContext,
            CancellationToken cancellationToken)
        {
            foreach (var handler in Handlers)
            {
                var result = await handler.Invoke(actionExecutedContext, cancellationToken);

                if (result != null)
                {
                    actionExecutedContext.Response = result;
                    return;
                }
            }
        }
        private static async Task<HttpResponseMessage> Handler400(
           HttpActionExecutedContext context,
           CancellationToken cancellationToken)
        {
            ValidationException validationException = context.Exception as ValidationException;
            if (validationException != null)
            {
                var exceptionResult = new NegotiatedContentResult<IEnumerable<ValidationResultDto>>(
                    HttpStatusCode.BadRequest,
                    validationException.ValidationResults.Select(r => new ValidationResultDto(r)),
                    context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(),
                    context.Request,
                    new MediaTypeFormatterCollection());
                return await exceptionResult.ExecuteAsync(cancellationToken);
            }

            var odataException = context.Exception as ODataException;
            if (odataException != null)
            {
                return context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception);
            }

            return null;
        }
Esempio n. 7
0
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
Esempio n. 8
0
 public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
 {
     actionExecutedContext.Response = actionExecutedContext.Request.CreateErrorResponse(HttpStatusCode.InternalServerError,
                                                                                        actionExecutedContext.Exception.Message);
     return(base.OnExceptionAsync(actionExecutedContext, cancellationToken));
 }
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            Console.WriteLine(actionExecutedContext.Exception);

            base.OnException(actionExecutedContext);
        }
Esempio n. 10
0
 public Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
 {
     return(Task.FromResult(0));
 }
Esempio n. 11
0
 /// <summary>
 /// 请求完成时
 /// </summary>
 /// <param name="actionExecutedContext"></param>
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     base.OnActionExecuted(actionExecutedContext);
 }
Esempio n. 12
0
 public async Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext,
                                               CancellationToken cancellationToken)
 {
 }
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     contextHelper.DisposeContext();
 }
Esempio n. 14
0
 private static HttpResponseMessage CreateBadRequestResponse(HttpActionExecutedContext actionExecutedContext, IEnumerable <string> mensagens)
 {
     return(CreateResponse(actionExecutedContext, HttpStatusCode.BadRequest, mensagens));
 }
Esempio n. 15
0
 private static HttpResponseMessage CreateErrorResponse(HttpActionExecutedContext actionExecutedContext, IEnumerable <string> mensagens)
 {
     return(CreateResponse(actionExecutedContext, HttpStatusCode.InternalServerError, mensagens));
 }
 /// <summary>
 /// Not implemented Async Call for Logging
 /// </summary>
 public Task ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
 {
     throw new System.NotImplementedException();
 }
Esempio n. 17
0
        private static Task <HttpResponseMessage> HandleCommonException(
            HttpActionExecutedContext context,
            bool useVerboseErros,
            CancellationToken cancellationToken)
        {
            var exception = context.Exception.Demystify();

            if (exception is AggregateException)
            {
                // In async call, the exception will be wrapped as AggregateException
                exception = exception.InnerException.Demystify();
            }

            if (exception == null)
            {
                return(Task.FromResult <HttpResponseMessage>(null));
            }

            var code = HttpStatusCode.InternalServerError;

            if (exception is ODataException)
            {
                code = HttpStatusCode.BadRequest;
            }
            else if (exception is SecurityException)
            {
                code = HttpStatusCode.Forbidden;
            }
            else if (exception is ResourceNotFoundException)
            {
                code = HttpStatusCode.NotFound;
            }
            else if (exception is PreconditionFailedException)
            {
                code = HttpStatusCode.PreconditionFailed;
            }
            else if (exception is PreconditionRequiredException)
            {
                code = (HttpStatusCode)428;
            }
            else if (context.Exception is NotImplementedException)
            {
                code = HttpStatusCode.NotImplemented;
            }

            // When exception occured in a ChangeSet request,
            // exception must be handled in OnChangeSetCompleted
            // to avoid deadlock in Github Issue #82.
            var changeSetProperty = context.Request.GetChangeSet();

            if (changeSetProperty != null)
            {
                changeSetProperty.Exceptions.Add(exception);
                changeSetProperty.OnChangeSetCompleted(context.Request);
            }

            if (code != HttpStatusCode.Unused)
            {
                if (useVerboseErros)
                {
                    return(Task.FromResult(context.Request.CreateErrorResponse(code, exception)));
                }

                return(Task.FromResult(context.Request.CreateErrorResponse(code, exception.Message)));
            }

            return(Task.FromResult <HttpResponseMessage>(null));
        }
Esempio n. 18
0
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //if (actionExecutedContext.Exception is TaskCanceledException)
            //{
            //    // TaskCanceledException is an exception representing a successful task cancellation
            //    // Don't need to log it
            //    // Ref: https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx
            //    return;
            //}

            //get the terminal error details
            var curTerminalError = actionExecutedContext.Exception;
            var curController    = actionExecutedContext.ActionContext.ControllerContext.Controller;
            var terminalName     = GetTerminalName(curController);

            HttpStatusCode statusCode = HttpStatusCode.InternalServerError;

            if (curTerminalError is AuthorizationTokenExpiredOrInvalidException)
            {
                statusCode = (HttpStatusCode)419;
            }
            else if (curTerminalError is AggregateException)
            {
                foreach (var innerEx in ((AggregateException)curTerminalError).InnerExceptions)
                {
                    if (innerEx is AuthorizationTokenExpiredOrInvalidException)
                    {
                        statusCode = (HttpStatusCode)419;
                    }
                }
            }

            //Post exception information to AppInsights
            Dictionary <string, string> properties = new Dictionary <string, string>();

            foreach (KeyValuePair <string, object> arg in actionExecutedContext.ActionContext.ActionArguments)
            {
                properties.Add(arg.Key, JsonConvert.SerializeObject(arg.Value));
            }
            properties.Add("Terminal", terminalName);
            new TelemetryClient().TrackException(curTerminalError, properties);

            string userId = null;

            if (!String.IsNullOrEmpty(actionExecutedContext.ActionContext.ControllerContext.RequestContext.Principal.Identity.AuthenticationType))
            {
                userId = actionExecutedContext.ActionContext.ControllerContext.RequestContext.Principal.Identity.AuthenticationType;
            }

            //POST event to fr8 about this terminal error
            new BaseTerminalController().ReportTerminalError(terminalName, curTerminalError, userId);


            //prepare the response JSON based on the exception type
            actionExecutedContext.Response = new HttpResponseMessage(statusCode);
            if (curTerminalError is TerminalCodedException)
            {
                //if terminal error is terminal Coded Exception, place the error code description in message
                var terminalEx    = (TerminalCodedException)curTerminalError;
                var terminalError =
                    JsonConvert.SerializeObject(new { status = "terminal_error", message = terminalEx.ErrorCode.GetEnumDescription() });
                actionExecutedContext.Response.Content = new StringContent(terminalError, Encoding.UTF8, "application/json");
            }
            else
            {
                var detailedMessage =
                    JsonConvert.SerializeObject(new { status = "terminal_error", message = curTerminalError.Message });
                actionExecutedContext.Response.Content = new StringContent(detailedMessage, Encoding.UTF8, "application/json");
            }
        }
Esempio n. 19
0
 public override void OnException(HttpActionExecutedContext contex)
 {
     contex.Response = contex.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Concat(contex.Exception.Message, " - ", contex.Exception.StackTrace));
 }
Esempio n. 20
0
        /// <summary>
        /// 在请求执行完后 记录请求的数据以及返回数据
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public override Task OnActionExecutedAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            object beginTime = null;

            if (actionExecutedContext.Request.Properties.TryGetValue(key, out beginTime))
            {
                var menuAction  = actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault();
                var menuAction1 = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes <MenuAttribute>().OfType <MenuAttribute>().FirstOrDefault();

                HttpRequestBase request = CurrentHttpContext.Instance().Request;
                DateTime        time    = DateTime.FromBinary(Convert.ToInt64(beginTime));
                //var accessChannelInfo = ConfigurationHelper.AccessChannelSetting; // load AccessChannel.xml

                SysOperationLog apiActionLog = new SysOperationLog();

                //提取Identity
                var id = CurrentHttpContext.Instance().User.Identity as ClaimsIdentity;
                if (id != null)
                {
                    int accessChannelId = 0;
                    int.TryParse(id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Actor)?.Value, out accessChannelId);

                    var appType = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.System)?.Value;
                    var token   = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Authentication)?.Value;
                    apiActionLog.SourceEquipment = appType;
                    apiActionLog.Token           = token;
                    var data = id?.Claims.FirstOrDefault(x => x.Type == ClaimTypes.UserData)?.Value;
                    if (data != null)
                    {
                        var user = JsonConvert.DeserializeObject <SysUser>(data);
                        if (user != null)
                        {
                            //获取用户token
                            apiActionLog.UserId = user.Id;
                        }
                    }
                }
                else
                {
                    apiActionLog.SourceEquipment = "未知";
                    //获取用户token
                    apiActionLog.UserId = 0;
                }

                //获取action名称
                apiActionLog.MethodAction = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                //获取Controller 名称
                apiActionLog.FunctionController = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                //获取action开始执行的时间
                apiActionLog.ExecutionTime = time;
                //获取执行action的耗时
                apiActionLog.ExecutionDuration = (DateTime.Now - time).Milliseconds;
                apiActionLog.Navigator         = request.UserAgent;
                //获取访问的ip
                ExploreHelper eh = new ExploreHelper(request);

                apiActionLog.ClientIpAddress = eh.ClientIP;
                //客户端名称
                apiActionLog.ClientName = eh.ClientMachineName;
                //Url来源
                apiActionLog.UrlReferrer = request.UrlReferrer != null ? request.UrlReferrer.AbsoluteUri : "";
                //浏览器信息
                apiActionLog.BrowserInfo = request.Browser.Browser + " - " + request.Browser.Version + " - " + request.Browser.Type;
                //获取request提交的参数
                apiActionLog.Parameters = GetRequestValues(actionExecutedContext) + " " + GetRequestActionValues(actionExecutedContext);

                //获取response响应的结果
                //apiActionLog.Exception = GetResponseValues(actionExecutedContext);
                // "",JsonConvert.SerializeObject(actionExecutedContext.Response.RequestMessage);
                try
                {
                    apiActionLog.IPNum = (int)StringHelper.IPToInt(eh.ClientIP);
                }
                catch
                {
                    apiActionLog.IPNum = 0;
                }
                apiActionLog.Description = msg;

                apiActionLog.RequestUri = request.Url.AbsoluteUri;
                apiActionLog.Enabled    = 1;
                WriteLogService.WriteLogOperate(apiActionLog);
            }
            return(base.OnActionExecutedAsync(actionExecutedContext, cancellationToken));
        }
Esempio n. 21
0
 public override void OnActionExecuted(HttpActionExecutedContext filterContext)
 {
     _stopWatch.Stop();
     Log(filterContext.ActionContext, _stopWatch.ElapsedMilliseconds);
 }
Esempio n. 22
0
 /// <summary>
 /// called when an exeption occurs.
 /// </summary>
 /// <param name="actionExecutedContext"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
 {
     return(base.OnExceptionAsync(actionExecutedContext, cancellationToken));
 }
Esempio n. 23
0
 private static HttpResponseMessage CreateResponse(HttpActionExecutedContext actionExecutedContext, HttpStatusCode codigo, IEnumerable <string> mensagens)
 {
     return(actionExecutedContext.Request.CreateResponse(codigo, mensagens));
 }
Esempio n. 24
0
 public override void OnException(HttpActionExecutedContext context)
 {
     context.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
 }
 /// <summary>
 /// 当WebApi Action发生异常
 /// </summary>
 /// <param name="actionExecutedContext">HttpActionExecutedContext</param>
 /// <param name="actionName">WebApi Action名称</param>
 /// <param name="statusCode">HttpStatusCode</param>
 /// <param name="requestRaw">Request原始信息</param>
 public abstract void OnActionExceptioning(HttpActionExecutedContext actionExecutedContext, string actionName, HttpStatusCode statusCode, HttpRequestRaw requestRaw);
Esempio n. 26
0
 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     Logger.Error(actionExecutedContext.Exception, "Unexpected API exception");
 }
Esempio n. 27
0
 public override void OnActionExecuted(HttpActionExecutedContext context)
 {
     _tracerService.SafeDispose();             // work is performed in the inner Disposed() method or the _tracerService instance
     _tracerService = null;
 }
Esempio n. 28
0
 Task IExceptionFilter.ExecuteExceptionFilterAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
 {
     throw new NotImplementedException();
 }
        /// <summary>
        /// Action执行完成的过滤器
        /// </summary>
        /// <param name="actionExecutedContext">操作执行的上下文</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

            // 不处理异常事件,异常由ExceptionFilter进行处理
            if (actionExecutedContext.Exception != null)
            {
                return;
            }

            // 不处理http状态码为200的action,例如路由不匹配action等则无须处理
            if (actionExecutedContext.Response.StatusCode != HttpStatusCode.OK && actionExecutedContext.Response.StatusCode != HttpStatusCode.NoContent)
            {
                return;
            }

            // 特殊处理,当HttpStatusCode.NoContent时也当作HttpStatusCode.OK处理,因为客户端就只验证状态码为200,对于204状态码会当作异常处理
            if (actionExecutedContext.Response.StatusCode == HttpStatusCode.NoContent)
            {
                actionExecutedContext.Response.StatusCode = HttpStatusCode.OK;
            }

            // 来访信息,日志用。
            var method = actionExecutedContext.Request.Method;
            var client = GetClientIP(actionExecutedContext.Request);
            var reqUrl = client + "=>" + method.Method + "=>" + actionExecutedContext.Request.RequestUri.ToString();

            // 检查请求头(headers)是否设"Accept", 如果设了"Accept"必须有要接受/json格式
            if (actionExecutedContext.Request.Headers != null)
            {
                var headers = actionExecutedContext.Request.Headers;
                var accept  = headers.FirstOrDefault(o => o.Key.ToLower() == "accept").Value;
                if (accept != null)
                {
                    var acceptJsons = accept.Where(x => (x.ToLower().Contains("*/*") || x.ToLower().Contains("json")) && !x.ToLower().Contains("q=0")).ToList();
                    if (acceptJsons.Count <= 0)
                    {
                        throw new ArgumentException("Headers指定了Accept但没有接受json格式。请不要设置Accept或设置Accept时需要包含接受json格式!" + reqUrl);
                    }
                }
            }

            var responseinfo = new ResponseInfo <Object>();

            //写入回复
            try
            {
                var returntype = actionExecutedContext.ActionContext.ActionDescriptor.ReturnType;
                if (returntype != null)
                {
                    var resultstring = "";
                    if (actionExecutedContext.Response.Content != null)
                    {
                        resultstring = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
                        //Type genericType = typeof(RequestInfo<>);
                        //Type[] templateTypeSet = new[] { postargument.Value.GetType() };
                        responseinfo.dataMap = JsonConvert.DeserializeObject(resultstring, returntype);
                    }
                }

                if (responseinfo.dataMap != null)
                {
                    var sign = SignBuilder.BuildSign(responseinfo.dataMap, "", "");
                    responseinfo.sign     = sign.Sign;
                    responseinfo.respTime = sign.ReqTime;
                }
                responseinfo.respCode = "0";
                responseinfo.respMsg  = "接口调用成功!";
                responseinfo.reqTime  = actionExecutedContext.Request.Headers.GetValues("resTime").FirstOrDefault();

                var s = JsonConvert.SerializeObject(responseinfo);
                actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse <ResponseInfo <Object> >(responseinfo);
            }
            catch (Exception ex)
            {
                throw new Exception("设置签名信息失败!" + reqUrl);
            }
        }
Esempio n. 30
0
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     actionExecutedContext.Response.Headers.Add(AccessControlAllowOrigin, originHeaderdefault);
 }
        private static Task<HttpResponseMessage> Handler404(
            HttpActionExecutedContext context,
            CancellationToken cancellationToken)
        {
            var notSupportedException = context.Exception as NotSupportedException;
            if (notSupportedException != null)
            {
                // TODO (.NETCORE) - TargetSite is not available.
                //if (notSupportedException.TargetSite.DeclaringType == typeof(RestierQueryBuilder))
                //{
                //    throw new HttpResponseException(context.Request.CreateErrorResponse(
                //        HttpStatusCode.NotFound,
                //        notSupportedException.Message));
                //}
            }

            return Task.FromResult<HttpResponseMessage>(null);
        }
        public override void OnException(HttpActionExecutedContext context)
        {
            GlobalConfiguration.Configuration.Services.Replace(typeof(ITraceWriter), new AppLogger());
            var logger = new AppLogger();

            logger.Error(context.Request, "Controller: " + context.ActionContext.ControllerContext.ControllerDescriptor.ControllerType.FullName + Environment.NewLine + "Action : " + context.ActionContext.ActionDescriptor.ActionName, TraceLevel.Error, context.Exception);

            var exceptionType = context.Exception.GetType();

            if (exceptionType == typeof(ValidationException))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
                {
                    Content = new StringContent(context.Exception.Message), ReasonPhrase = "ValidationException",
                };
                throw new HttpResponseException(resp);
            }
            else if (exceptionType == typeof(UnauthorizedAccessException))
            {
                throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.Unauthorized, new ServiceStatus()
                {
                    StatusCode = (int)HttpStatusCode.Unauthorized, StatusMessage = "UnAuthorized", ReasonPhrase = "UnAuthorized Access"
                }));
            }
            else if (exceptionType == typeof(ApiException))
            {
                var webapiException = context.Exception as ApiException;
                if (webapiException != null)
                {
                    throw new HttpResponseException(context.Request.CreateResponse(webapiException.HttpStatus, new ServiceStatus()
                    {
                        StatusCode = webapiException.ErrorCode, StatusMessage = webapiException.ErrorDescription, ReasonPhrase = webapiException.ReasonPhrase
                    }));
                }
            }
            else if (exceptionType == typeof(ApiBusinessException))
            {
                var businessException = context.Exception as ApiBusinessException;
                if (businessException != null)
                {
                    throw new HttpResponseException(context.Request.CreateResponse(businessException.HttpStatus, new ServiceStatus()
                    {
                        StatusCode = businessException.ErrorCode, StatusMessage = businessException.ErrorDescription, ReasonPhrase = businessException.ReasonPhrase
                    }));
                }
            }
            else if (exceptionType == typeof(ApiDataException))
            {
                var dataException = context.Exception as ApiDataException;
                if (dataException != null)
                {
                    throw new HttpResponseException(context.Request.CreateResponse(dataException.HttpStatus, new ServiceStatus()
                    {
                        StatusCode = dataException.ErrorCode, StatusMessage = dataException.ErrorDescription, ReasonPhrase = dataException.ReasonPhrase
                    }));
                }
            }
            else
            {
                var errorMessage = GetErrorMessage(context);
                throw new HttpResponseException(context.Request.CreateResponse(HttpStatusCode.InternalServerError,
                                                                               new
                {
                    Message = errorMessage
                }));
            }
        }
 public static HttpResponseMessage HandleExecutedContextException(this HttpActionExecutedContext context)
 {
     // Retorna a resposta para o cliente com o erro 500 e o ExceptionPayload (código de erro de negócio e mensagem)
     return(context.Request.CreateResponse(HttpStatusCode.InternalServerError, ExceptionPayload.New(context.Exception)));
 }
Esempio n. 34
0
        /// <summary>
        /// Create a text description of the request
        /// </summary>
        private static string CaptureRequestDetails(HttpActionExecutedContext context, object preamble = null)
        {
            const int maxMessageSize = 20000;

            // Handle null request (just in case?)
            if (context == null || context.Request == null)
            {
                return(preamble == null ? "" : preamble.ToString( ));
            }

            // Set up string builder
            using (TextWriter writer = new StringWriter())
            {
                try
                {
                    if (preamble != null)
                    {
                        writer.WriteLine(preamble.ToString( ));
                    }

                    // Write method and URI
                    HttpRequestMessage request = context.Request;
                    writer.WriteLine( );
                    writer.WriteLine("Uri: {0} {1}", request.Method, request.RequestUri);

                    // Log the controller
                    writer.WriteLine("Controller: {0}", context.ActionContext.ControllerContext.Controller.GetType( ).FullName);

                    // Log decoded parameters
                    // (Unfortunately we can't easily get to the raw request body, so we have to settle for reserializing them)
                    if (!(context.ActionContext.ControllerContext.Controller is LoginController))
                    {
                        writer.WriteLine("Action Arguments:");
                        writer.WriteLine("(caution: reserialized data, not original message!)");
                        var options = new Options(true, false, false, DateTimeFormat.ISO8601, true);

                        foreach (var pair in context.ActionContext.ActionArguments)
                        {
                            writer.Write(pair.Key);
                            writer.Write(" = ");
                            try
                            {
                                JSON.Serialize(pair.Value, writer, options);
                            }
                            catch
                            {
                                writer.Write("can't reserialize");
                            }
                            writer.WriteLine( );
                        }
                    }
                }
                catch (Exception ex)
                {
                    writer.WriteLine( );
                    writer.WriteLine("Failed to log request:");
                    writer.WriteLine(ex);
                }

                string message = writer.ToString();
                if (message.Length > maxMessageSize)
                {
                    message = message.Substring(0, maxMessageSize);
                }
                return(message);
            }
        }
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     ServiceEventSource.Current.ServiceRequestStop(actionExecutedContext.ActionContext.ActionDescriptor.ActionName,
                                                   actionExecutedContext.Exception?.ToString() ?? string.Empty);
 }
Esempio n. 36
0
 public void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     // do we need to implement anything here?
 }
Esempio n. 37
0
 private HttpAfterActionMessage(HttpActionExecutedContext context)
 {
     _context = context;
 }
 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     OnActionExecuted(HttpContext.Current,
                                  () => base.OnActionExecuted(actionExecutedContext));
 }
Esempio n. 39
0
 public override void OnException(HttpActionExecutedContext context)
 {
 }