• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C# Filters.HttpActionExecutedContext类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中System.Web.Http.Filters.HttpActionExecutedContext的典型用法代码示例。如果您正苦于以下问题:C# HttpActionExecutedContext类的具体用法?C# HttpActionExecutedContext怎么用?C# HttpActionExecutedContext使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



HttpActionExecutedContext类属于System.Web.Http.Filters命名空间,在下文中一共展示了HttpActionExecutedContext类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。

示例1: OnException

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
            {

                var exception = actionExecutedContext.Exception;
                var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                var controllerName = actionExecutedContext.ActionContext.ControllerContext.ControllerDescriptor.ControllerName;

                string resourceFile = String.IsNullOrEmpty(LocalResourceFile) 
                                        ? Localization.ExceptionsResourceFile 
                                        : LocalResourceFile;

                string key = String.IsNullOrEmpty(MessageKey) ? controllerName + "_" + actionName + ".Error" : MessageKey;

                var response = new HttpResponseMessage
                                        {
                                            StatusCode = HttpStatusCode.InternalServerError,
                                            ReasonPhrase = Localization.GetString(key, resourceFile)
                                        };
                
                actionExecutedContext.Response = response;

                Exceptions.LogException(exception);
            }
        }
开发者ID:VegasoftTI,项目名称:Dnn.Platform,代码行数:26,代码来源:DnnExceptionAttribute.cs


示例2: OnException

 public override void OnException(HttpActionExecutedContext context)
 {
     if (context.Exception is ValidationException)
     {
         RespondWithBadRequest(context);
     }
 }
开发者ID:je-saan,项目名称:JE.ApiValidation,代码行数:7,代码来源:ResponseProcessingErrorAttribute.cs


示例3: OnException

        public override void OnException(HttpActionExecutedContext context)
        {
            if (MvcApplication.Logger != null && context.Exception != null)
            {
                MvcApplication.Logger.Error("ExceptionHandlingAttribute", context.Exception);
            }

            if (context.Exception is System.Data.DataException)
            {
                throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent(context.Exception.Message),
                    ReasonPhrase = "Exception"
                });
            }

            //Log Critical errors
            Debug.WriteLine(context.Exception);

            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content = new StringContent("An error occurred, please try again or contact the administrator."),
                ReasonPhrase = "Critical Exception"
            });
        }
开发者ID:OleksandrKulchytskyi,项目名称:Sharedeployed,代码行数:25,代码来源:HandledErrorLoggerFilter.cs


示例4: OnActionExecuted

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var buffer = TraceBuffer.Current;

            if (buffer == null)
            {
                return;
            }

            TraceBuffer.Clear();

            if (buffer.HasContent)
            {
                string originalContent;
                HttpStatusCode statusCode;

                if (actionExecutedContext.Exception == null)
                {
                    originalContent = actionExecutedContext.Response.Content.ReadAsStringAsync().Result;
                    statusCode = actionExecutedContext.Response.StatusCode;
                }
                else
                {
                    originalContent = actionExecutedContext.Exception.ToLogString();
                    statusCode = HttpStatusCode.InternalServerError;
                }

                actionExecutedContext.Response = new HttpResponseMessage(statusCode)
                {
                    Content = new StringContent(string.Format("{0}\n\n{1}", buffer, originalContent).Trim())
                };
            }
        }
开发者ID:wli3,项目名称:Its.Log,代码行数:33,代码来源:TracingFilter.cs


示例5: End

        private void End(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception != null)
                WindsorAccessor.Instance.Container.Resolve<IUnitOfWork>().Abort();

            WindsorAccessor.Instance.Container.Resolve<IUnitOfWork>().End();
        }
开发者ID:brucewu16899,项目名称:lacjam,代码行数:7,代码来源:TransactionalAttribute.cs


示例6: OnActionExecuted

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

        base.OnActionExecuted(actionExecutedContext);
    }
开发者ID:jthoni,项目名称:matcheckin,代码行数:7,代码来源:ControllerAttributes.cs


示例7: OnActionExecuted

 public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
 {
     try
     {
         //Apply logging
         var objChanges = HttpContext.Current.Items[ContactInfo.CONTACT_CHANGE] as List<ActivityObjectChangeInfo>;
         if (objChanges != null)
         {
             var activityInfo = new ActivityLogInfo
                                    {
                                        FunctionId = 0,
                                        CreatedBy = UserContext.GetCurrentUser().UserID
                                    };
             activityInfo.Id = ActivityLogRepository.Create(activityInfo);
             foreach (var objChange in objChanges)
             {
                 objChange.ActivityId = activityInfo.Id;
                 ActivityObjectChangeRepository.Create(objChange);
             }
         }
         HttpContext.Current.Items[ContactInfo.CONTACT_CHANGE] = null;
     }
     catch
     {
         //Dont throw exception if loging failed
     }
     base.OnActionExecuted(actionExecutedContext);
 }
开发者ID:haoas,项目名称:CRMTPE,代码行数:28,代码来源:WebApiLogActionFilter.cs


示例8: OnException

 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Exception is DraftAuthenticationException)
     {
         actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized)
         {
             Content = new StringContent("Unauthorized"),
             ReasonPhrase = "Unauthorized"
         };
     }
     else if (actionExecutedContext.Exception is HttpStatusException)
     {
         HttpStatusException exc = (HttpStatusException)actionExecutedContext.Exception;
         actionExecutedContext.Response = new HttpResponseMessage(exc.Status)
         {
             Content = new StringContent(exc.Message),
             ReasonPhrase = exc.Message
         };
     }
     else if (actionExecutedContext.Exception != null)
     {
         Exception exc = actionExecutedContext.Exception;
         actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
         {
             Content = new StringContent(exc.Message),
             ReasonPhrase = exc.Source + " : " + exc.GetType().ToString() + " : " + exc.Message
         };
     }
 }
开发者ID:nmielnik,项目名称:fantasyDraft,代码行数:29,代码来源:DraftExceptionFilter.cs


示例9: OnException

 public override void OnException(HttpActionExecutedContext actionExecutedContext)
 {
     if (actionExecutedContext.Exception is BadRequestException)
     {
         actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, new HttpError(actionExecutedContext.Exception.Message));
     }
 }
开发者ID:ddraganov,项目名称:FMI-WebDev2015,代码行数:7,代码来源:BadRequestExceptionAttribute.cs


示例10: OnActionExecuted

        /// <summary>
        /// Called when the action is executed.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);

              if (!actionExecutedContext.Response.IsSuccessStatusCode) {
            return;
              }

              object responseObject;
              if (!actionExecutedContext.Response.TryGetContentValue(out responseObject)) {
            return;
              }

              var queryable = ApplySelectAndExpand(responseObject as IQueryable, actionExecutedContext.Request);
              if (queryable != null) {
            // if a select or expand was encountered we need to
            // execute the DbQueries here, so that any exceptions thrown can be properly returned.
            // if we wait to have the query executed within the serializer, some exceptions will not
            // serialize properly.
            var rQuery = Enumerable.ToList((dynamic) queryable);

            var formatter = ((dynamic) actionExecutedContext.Response.Content).Formatter;
            var oc = new ObjectContent(rQuery.GetType(), rQuery, formatter);
            actionExecutedContext.Response.Content = oc;
              }

              Object tmp;
              actionExecutedContext.Request.Properties.TryGetValue("MS_InlineCount", out tmp);
              var inlineCount = (Int64?) tmp;

              if (inlineCount.HasValue) {
            actionExecutedContext.Response.Headers.Add("X-InlineCount", inlineCount.ToString());
              }
        }
开发者ID:adaptabi,项目名称:Breeze,代码行数:38,代码来源:BreezeQueryableAttribute.cs


示例11: OnException

        public override void OnException(HttpActionExecutedContext context)
        {
            HttpStatusCode status = HttpStatusCode.InternalServerError;

            var exType = context.Exception.GetType();

            if (exType == typeof(UnauthorizedAccessException))
                status = HttpStatusCode.Unauthorized;
            else if (exType == typeof(ArgumentException))
                status = HttpStatusCode.NotFound;
            else if (exType == typeof(ServiceUnavailableExceptions))
                status = HttpStatusCode.ServiceUnavailable;
            else if (exType == typeof(InvalidOperationException)) // Happens when someone tries to Update on POST instead of PUT.
                status = HttpStatusCode.MethodNotAllowed;
            else if (exType == typeof(ItemNotFoundException))
                status = HttpStatusCode.NotFound;

            var apiError = new ApiMessageError() { message = context.Exception.Message };

            // create a new response and attach our ApiError object
            // which now gets returned on ANY exception result
            var errorResponse = context.Request.CreateResponse<ApiMessageError>(status, apiError);
            context.Response = errorResponse;
            errorResponse.ReasonPhrase = context.Exception.Message;

            base.OnException(context);
        }
开发者ID:sondreb,项目名称:InTheBoks,代码行数:27,代码来源:UnhandledExceptionFilter.cs


示例12: OnException

 public override void OnException(HttpActionExecutedContext context)
 {
     if (context.Exception is ArgumentNullException)
     {
         context.Response = context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "ArgumentNullException occurred");
     }
 }
开发者ID:gkudel,项目名称:Testility,代码行数:7,代码来源:ArgumentNullExceptionFilterAttribute.cs


示例13: OnActionExecuted

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Response != null)
                actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", ConfigurationManager.AppSettings["ClientUrl"]);

            base.OnActionExecuted(actionExecutedContext);
        }
开发者ID:alexandrupero,项目名称:CommentBox,代码行数:7,代码来源:AllowCrossSiteJsonAttribute.cs


示例14: OnException

        /// <summary>
        /// Raises the exception event.
        /// </summary>
        /// <param name="context">The context for the action.</param>
        public override void OnException(HttpActionExecutedContext context)
        {
            var wrapResultAttribute = HttpActionDescriptorHelper
                .GetWrapResultAttributeOrNull(context.ActionContext.ActionDescriptor) ??
                _configuration.DefaultWrapResultAttribute;

            if (wrapResultAttribute.LogError)
            {
                LogHelper.LogException(Logger, context.Exception);
            }

            if (!wrapResultAttribute.WrapOnError)
            {
                return;
            }

            if (IsIgnoredUrl(context.Request.RequestUri))
            {
                return;
            }

            context.Response = context.Request.CreateResponse(
                GetStatusCode(context),
                new AjaxResponse(
                    SingletonDependency<ErrorInfoBuilder>.Instance.BuildForException(context.Exception),
                    context.Exception is Abp.Authorization.AbpAuthorizationException)
            );

            EventBus.Trigger(this, new AbpHandledExceptionData(context.Exception));
        }
开发者ID:sessionliang,项目名称:aspnetboilerplate,代码行数:34,代码来源:AbpApiExceptionFilterAttribute.cs


示例15: GetContactLink

 Uri GetContactLink(int contactId, HttpActionExecutedContext context)
 {
     var routeData = context.Request.GetRouteData();
     var controller = routeData.Values["controller"];
     var urlHelper = context.Request.GetUrlHelper();
     return new Uri(urlHelper.Route("DefaultApi", new { controller = controller, id = contactId }), UriKind.Relative);
 }
开发者ID:julid29,项目名称:confsamples,代码行数:7,代码来源:ContactSelfLinkFilter.cs


示例16: GetActionExecutedContext

 public static HttpActionExecutedContext GetActionExecutedContext(HttpRequestMessage request, HttpResponseMessage response)
 {
     HttpActionContext actionContext = CreateActionContext();
     actionContext.ControllerContext.Request = request;
     HttpActionExecutedContext actionExecutedContext = new HttpActionExecutedContext(actionContext, null) { Response = response };
     return actionExecutedContext;
 }
开发者ID:Rhombulus,项目名称:aspnetwebstack,代码行数:7,代码来源:ContextUtil.cs


示例17: HandleJsonException

        private static void HandleJsonException(HttpActionExecutedContext ec)
        {
            ErrorDto data = new ErrorDto();

            // Different data depending on exception type
            var exceptionType = ec.Exception.GetType();
            if (exceptionType == typeof(BrokenRuleException))
            {
                data.BrokenRules = GetDistinctBrokenRules(((BrokenRuleException) ec.Exception).BrokenRules);
            }
            else if (exceptionType == typeof(UserFriendlyException))
            {
                data.Message = ec.Exception.Message.Replace("\r\n", "<br/>");
            }
            else
            {
                data.Message = string.Format("An unexpected error has occurred. Please try agian.");
            }

            ec.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError)
            {
                Content =
                    new ObjectContent<ErrorDto>(
                        data,
                        new JsonMediaTypeFormatter() {UseDataContractJsonSerializer = false})
            };
        }
开发者ID:MetalKid,项目名称:ThatConference-Aurelia,代码行数:27,代码来源:HandleExceptionAttribute.cs


示例18: OnActionExecuted

        /// <summary>
        /// Called when the action is executed.  If the return type is IEnumerable or IQueryable, 
        /// calls OnActionExecuted in the base class, which in turn calls ApplyQuery.
        /// </summary>
        /// <param name="actionExecutedContext">The action executed context.</param>
        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            var response = actionExecutedContext.Response;
              if (response == null || !response.IsSuccessStatusCode) {
            return;
              }

              object responseObject;
              if (!response.TryGetContentValue(out responseObject)) {
            return;
              }

              var request = actionExecutedContext.Request;
              var returnType = actionExecutedContext.ActionContext.ActionDescriptor.ReturnType;
              var queryHelper = GetQueryHelper(request);
              if (typeof(IEnumerable).IsAssignableFrom(returnType) || responseObject is IEnumerable) {
            // QueryableAttribute only applies for IQueryable and IEnumerable return types
            base.OnActionExecuted(actionExecutedContext);
            if (!actionExecutedContext.Response.IsSuccessStatusCode) {
              return;
            }
            if (!response.TryGetContentValue(out responseObject)) {
              return;
            }
            var queryResult = queryHelper.ApplySelectAndExpand(responseObject as IQueryable, request.RequestUri.ParseQueryString());
            queryHelper.WrapResult(request, response, queryResult);
              } else {
            // For non-IEnumerable results, post-processing must be done manually by the developer.
              }

              queryHelper.ConfigureFormatter(actionExecutedContext.Request, responseObject as IQueryable);
        }
开发者ID:nateClicks,项目名称:Breeze,代码行数:37,代码来源:BreezeQueryableAttribute.cs


示例19: OnException

 public override void OnException(HttpActionExecutedContext context)
 {
     if (context.Exception is ApplicationException)
     {
        context.Response= context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception.Message);
     }
 }
开发者ID:goodwillguy,项目名称:DeviceManagerService,代码行数:7,代码来源:ApplicationExceptionFilter.cs


示例20: OnException

        public override void OnException(HttpActionExecutedContext ctx)
        {
            if (!IgnoreExceptions.Contains(ctx.Exception.GetType()))
            {
                var statusCode = GetStatus(ctx.Exception.GetType());

                var error = new HttpError(ctx.Exception, IncludeErrorDetails(ctx));

                var req = ctx.Request;

                var exLog = ctx.Exception.LogException(e =>
                {
                    e.ActionName = ctx.ActionContext.ActionDescriptor.ActionName;
                    e.ControllerName = ctx.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                    e.UserAgent = req.Headers.UserAgent.ToString();
                    e.RequestUrl = req.RequestUri.ToString();
                    e.UrlReferer = req.Headers.Referrer?.ToString();
                    e.UserHostAddress = GetClientIp(req);
                    e.UserHostName = GetClientName(req);
                    e.QueryString = ExceptionEntity.Dump(req.RequestUri.ParseQueryString());
                    e.Form = (string)(req.Properties.ContainsKey(SignumAuthenticationAndProfilerAttribute.SavedRequestKey) ? req.Properties[SignumAuthenticationAndProfilerAttribute.SavedRequestKey] : null);
                    e.Session = GetSession(req);
                });

                error["ExceptionID"] = exLog.Id.ToString();

                ctx.Response = ctx.Request.CreateResponse<HttpError>(statusCode, error);
            }

            base.OnException(ctx);
        }
开发者ID:signumsoftware,项目名称:framework,代码行数:31,代码来源:SignumExceptionFilterAttribute.cs



注:本文中的System.Web.Http.Filters.HttpActionExecutedContext类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Metadata.ModelMetadata类代码示例发布时间:2022-05-26
下一篇:
C# ExceptionHandling.ExceptionLoggerContext类代码示例发布时间:2022-05-26
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap