예제 #1
0
 private string GenObjectString(JsonErrorResult res)
 {
     return(JsonConvert.SerializeObject(res, Formatting.Indented, new JsonSerializerSettings()
     {
         ContractResolver = new CamelCasePropertyNamesContractResolver()
     }));
 }
        /// <summary>
        /// Handles the standard filter method.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnException(ExceptionContext filterContext)
        {
            JsonErrorResult errorResult;

            if (
                // has the exception already been handled?
                filterContext.ExceptionHandled
                // there gots to be an exception!
                || (filterContext.Exception == null)
                )
            {
                // don't process it, just return
                return;
            }

            // if an exception type has been defined and the exception is NOT that type
            if (this.ExceptionType != null && this.ExceptionType != filterContext.Exception.GetType())
            {
                return;
            }

            // if we only care about handling on ajax requests and this is NOT one...
            if (AjaxOnlyRequest && !filterContext.RequestContext.HttpContext.Request.IsAjaxRequest())
            {
                // ... then don't do anything.
                return;
            }

            // if 1 or more accept types have been specified,
            if (AcceptTypes != null && AcceptTypes.Length > 0)
            {
                // see that at least 1 of the types exists in both lists.
                if (AcceptTypes.Join(filterContext.HttpContext.Request.AcceptTypes, t => t, t => t, (t, r) => t).Count() == 0)
                {
                    return;
                }
            }

            errorResult = JsonErrorResult.Create(IncludeException ? filterContext.Exception : null, this.Message);

            // set the call result to the JSON error result package
            filterContext.Result = new JsonResult()
            {
                Data = errorResult, JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
            // mark the exception as handled to stop further error filter handling

            filterContext.HttpContext.Response.StatusCode = HttpStatusCode;
            filterContext.ExceptionHandled = true;

            NotifyExceptionHandled(filterContext);
        }
예제 #3
0
        public void OnException(ExceptionContext context)
        {
            var json = new JsonErrorResult();

            if (context.Exception.GetType() == typeof(MyExcepton))
            {
                json.Message   = context.Exception.Message;
                context.Result = new BadRequestObjectResult(json);
            }
            else
            {
                json.Message = "发生了未知的内部错误";
                if (_env.IsDevelopment())
                {
                    json.DeveloperMessage = context.Exception.StackTrace;
                }
                context.Result = new InternalServerErrorObjectResult(json);
            }
            _logger.LogError(context.Exception, context.Exception.Message);
            context.ExceptionHandled = true;
        }
 /// <summary>
 /// Handler override.
 /// </summary>
 /// <param name="filterContext"></param>
 protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
 {
     // We are NOT authenticated
     if (filterContext.HttpContext.Request.IsAjaxRequest())
     {
         filterContext.Result = new JsonResult()
         {
             Data = JsonErrorResult.Create(new UnauthorizedAccessException(), _jsonMessage),
             JsonRequestBehavior = JsonRequestBehavior.AllowGet
         };
     }
     else
     {
         if (!string.IsNullOrEmpty(_errorView))
         {
             filterContext.Result = new ViewResult()
             {
                 ViewName = _errorView,
                 ViewData = filterContext.Controller.ViewData,
                 TempData = filterContext.Controller.TempData,
             };
         }
     }
 }
예제 #5
0
        public async Task Invoke(HttpContext ctx)
        {
            JsonErrorResult res = null;

            try
            {
                await _next(ctx);
            }
            catch (InvalidCredentials)
            {
                res = new JsonErrorResult()
                {
                    Code     = "401:Unauthorized",
                    Message  = "Invalid credentials",
                    Resource = "Not applicable",
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 401;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
            catch (Shared.Exceptions.InsuficientPermission ex)
            {
                res = new JsonErrorResult()
                {
                    Code     = "403:Forbidden",
                    Message  = "Missing required permission : '" + ex.MissingPermission + "'",
                    Resource = ex.ResourceType.ToString() + ":" + ex.ResourceName + ":" + ex.ResourceId,
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 403;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
            catch (Shared.Exceptions.InvalidResource ex)
            {
                res = new JsonErrorResult()
                {
                    Code     = "400:Invalid",
                    Message  = "Invalid property : '" + ex.PropertyName + "'",
                    Resource = ex.ResourceType.ToString() + ":" + ex.ResourceName,
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 400;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
            catch (Shared.Exceptions.ResourceAlreadyExists ex)
            {
                res = new JsonErrorResult()
                {
                    Code     = "409:Conflict",
                    Message  = "Resource already exists",
                    Resource = ex.ResourceType.ToString() + ":" + ex.ResourceName + ":" + ex.ResourceId,
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 409;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
            catch (Shared.Exceptions.ResourceNotFound ex)
            {
                res = new JsonErrorResult()
                {
                    Code     = "404:NotFound",
                    Message  = "The specified resource could not be found",
                    Resource = ex.ResourceType.ToString() + ":" + ex.ResourceName + ":" + ex.ResourceId,
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 404;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
            catch (Exception ex)
            {
                _telemetryClient.TrackException(ex);
                res = new JsonErrorResult()
                {
                    Code     = "500:Internal",
                    Message  = ex.GetType().ToString() + ": " + ex.Message,
                    Resource = "An unhandled exception occured while processing your request",
                    Route    = ctx.Request.Path
                };
                ctx.Response.Clear();
                ctx.Response.ContentType = "application/json";
                ctx.Response.StatusCode  = 500;
                PutCORSHeaders(ctx);
                await ctx.Response.WriteAsync(GenObjectString(res));
            }
        }