/// <summary>
        /// 异步发送post请求,带json数据,有返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <typeparam name="V"></typeparam>
        /// <param name="address"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public static async Task <V> PostJsonAsync <T, V>(string address, T value)
        {
            try
            {
                var response = await httpClient.PostAsJsonAsync(address, value);

                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <V>());
                }
                else
                {
                    var apiErrorModel = await response.Content.ReadAsAsync <ApiErrorModel>();

                    throw new ApiErrorException(apiErrorModel);
                }
            }
            catch (Exception er)
            {
                var apiErrorModel = new ApiErrorModel()
                {
                    StatusCode = HttpStatusCode.NotFound,
                    Message    = "网络连接错误",
                    Code       = 3
                };
                throw new ApiErrorException(apiErrorModel);
            }
        }
Exemple #2
0
        /// <summary>
        /// 异步发起get请求  有返回值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="address"></param>
        /// <returns></returns>
        public static async Task <T> GetAsync <T>(string address)
        {
            try
            {
                var response = await httpClient.GetAsync(address);

                if (response.IsSuccessStatusCode)
                {
                    return(await response.Content.ReadAsAsync <T>());
                }
                else
                {
                    var apiErrorModel = await response.Content.ReadAsAsync <ApiErrorModel>();

                    throw new ApiErrorException(apiErrorModel);
                }
            }
            catch (Exception er)
            {
                if (!(er is ApiErrorException))
                {
                    var apiErrorModel = new ApiErrorModel()
                    {
                        StatusCode = HttpStatusCode.NotFound,
                        Message    = "网络连接错误",
                        Code       = 3
                    };
                    throw new ApiErrorException(apiErrorModel);
                }
                else
                {
                    throw er;
                }
            }
        }
        public static async Task UploadFileAsync(string address, string fileName)
        {
            using (var httpClient = new HttpClient())
            {
                using (var content = new MultipartFormDataContent(fileName))
                    using (var stream = File.Open(fileName, FileMode.Open))
                    {
                        try
                        {
                            content.Add(new StreamContent(stream));
                            var response = await httpClient.PostAsync(address, content);

                            if (!response.IsSuccessStatusCode)
                            {
                                var apiErrorModel = await response.Content.ReadAsAsync <ApiErrorModel>();

                                throw new ApiErrorException(apiErrorModel);
                            }
                        }
                        catch (Exception er)
                        {
                            var apiErrorModel = new ApiErrorModel()
                            {
                                StatusCode = HttpStatusCode.NotFound,
                                Message    = "网络连接错误",
                                Code       = 3
                            };
                            throw new ApiErrorException(apiErrorModel);
                        }
                    }
            }
        }
Exemple #4
0
        public void ApiErrorModel_WhenJsonSerialized_HasExpectedProperties()
        {
            var model = new ApiErrorModel
            {
                ErrorCode    = 123,
                ErrorDetails = "error details",
                Message      = "message",
                RequestId    = "request id",
                StatusCode   = System.Net.HttpStatusCode.InternalServerError,
                Arguments    = new Dictionary <string, string>
                {
                    { "key1", "value1" },
                    { "key2", "value2" },
                }
            };

            var jsonObject = JObject.FromObject(model);

            Assert.Equal(model.Id, jsonObject["id"].Value <string>());
            Assert.Equal(model.RequestId, jsonObject["requestId"].Value <string>());
            Assert.Equal(model.StatusCode, jsonObject["statusCode"].ToObject <System.Net.HttpStatusCode>());
            Assert.Equal(model.ErrorCode, jsonObject["errorCode"].Value <int>());
            Assert.Equal(model.Message, jsonObject["message"].Value <string>());
            Assert.Equal(model.ErrorDetails, jsonObject["errorDetails"].Value <string>());
            Assert.Equal(model.Arguments, jsonObject["arguments"].ToObject <Dictionary <string, string> >());
        }
        public async Task <IServiceResult <string, ApiErrorModel> > GetSteamIdFromProfileUrlAsync(string url)
        {
            string steamId = string.Empty;

            try
            {
                steamId = await _steamService.Get64BitSteamIdAsync(url);

                _logger.Log(LogLevel.Debug, new EventId((int)LogEventId.General), $"SteamID for {url}: {steamId}");
            }
            catch (Exception ex)
            {
                //Type of error that is expected and should be relayed back to the client as a toast message
                _logger.Log(LogLevel.Error, new EventId((int)LogEventId.General), $"Failed to find Steam Id for {url}");
                _logger.Log(LogLevel.Error, new EventId((int)LogEventId.General), ex.ToString());
                var em = new ApiErrorModel()
                {
                    Errors = new List <string>()
                    {
                        $"No Steam profile found for {url}"
                    },
                    Type = ApiErrorModel.TYPE_TOAST_ERROR
                };

                return(ServiceResultFactory.Error <string, ApiErrorModel>(em));
            }
            return(ServiceResultFactory.Ok <string, ApiErrorModel>(steamId));
        }
        public async Task <IServiceResult <GameDetails, ApiErrorModel> > GetGameDetailsAsync(long appId)
        {
            try
            {
                var request  = (HttpWebRequest)WebRequest.Create(string.Format("https://store.steampowered.com/api/appdetails?appids={0}", appId));
                var response = (HttpWebResponse)await request.GetResponseAsync();

                var    reader       = new StreamReader(response.GetResponseStream());
                string jsonResponse = reader.ReadToEnd();
                var    gameDetails  = JObject.Parse(jsonResponse).SelectToken(appId.ToString())?.SelectToken("data")?.ToObject <GameDetails>();
                return(ServiceResultFactory.Ok <GameDetails, ApiErrorModel>(gameDetails));
            }
            catch (Exception ex)
            {
                var em = new ApiErrorModel()
                {
                    Errors = new List <string>()
                    {
                        ex.Message.Contains("429") ? "Rate limited" : ex.ToString()
                    },
                    Type = ApiErrorModel.TYPE_SERVER_ERROR
                };
                return(ServiceResultFactory.Error <GameDetails, ApiErrorModel>(em));
            }
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await _next(context);
            }
            catch (ApiException ex)
            {
                _logger.LogWarning(ex, $"Exception Code: {(int)ex.ExceptionCode}");

                ApiErrorModel payload = new ApiErrorModel
                {
                    ExceptionCode = ex.ExceptionCode,
                    Message       = ex.Message,
                    Exception     = _webHostEnvironment.IsDevelopment() ? ex.ToString() : ApiErrorConstants.NON_DEVELOPMENT_EXCEPTION_MESSAGE
                };

                await WriteAsJsonAsync(context, HttpStatusCode.BadRequest, payload);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, ex.Message);

                InternalServerErrorModel payload = new InternalServerErrorModel
                {
                    Message   = ex.Message,
                    Exception = _webHostEnvironment.IsDevelopment() ? ex.ToString() : InternalServerErrorConstants.NON_DEVELOPMENT_EXCEPTION_MESSAGE
                };

                await WriteAsJsonAsync(context, HttpStatusCode.InternalServerError, payload);
            }
        }
        private void TraceErrorEvent(ExceptionContext exceptionContext, ApiErrorModel error)
        {
            string message    = JsonConvert.SerializeObject(error);
            var    traceEvent = new TraceEvent(TraceLevel.Error, message, $"ApiError", exceptionContext.Exception);

            _traceWriterLoader.Value.Trace(traceEvent);
        }
Exemple #9
0
        /// <summary>
        /// Creates an <see cref="T:Microsoft.AspNetCore.Mvc.BadRequestObjectResult" /> that produces a Bad Request (400) response.
        /// </summary>
        /// <param name="modelState">the model state</param>
        /// <returns>
        /// The created <see cref="T:Microsoft.AspNetCore.Mvc.BadRequestObjectResult" /> for the response.
        /// </returns>
        public override BadRequestObjectResult BadRequest(ModelStateDictionary modelState)
        {
            var error = new ApiErrorModel();

            error.Code    = "BadArgument";
            error.Message = "Argumento invalido";

            foreach (var key in modelState.Keys)
            {
                var errorState = modelState[key];

                foreach (var detailError in errorState.Errors)
                {
                    error.Details.Add(new ApiErrorModel()
                    {
                        Code    = "BadArgument",
                        Message = detailError.ErrorMessage,
                        Target  = key
                    });
                }
            }

            return(base.BadRequest(new BaseApiErrorModel()
            {
                Error = error
            }));
        }
        public async Task Invoke(HttpContext context)
        {
            try
            {
                await this.next(context);
            }
            catch (Exception ex)
            {
                var requestDetails = JsonSerializer.Serialize(LogDetailedFactory.GetModel(ex, context));

                this.logger.LogError(ex, $"{ex} RequestData: {{requestDetails}}".ToString(), requestDetails);

                var jsonResponse = new ApiErrorModel()
                {
                    Code    = "ServerError",
                    Message = this.env.IsDevelopment() ? ex.ToString() : "Error inesperado, intene de nuevo"
                };

                string jsonString = JsonSerializer.Serialize <ApiErrorModel>(jsonResponse, this.options);

                context.Response.StatusCode  = 500;
                context.Response.ContentType = "application/json";

                await context.Response.WriteAsync(jsonString, System.Text.Encoding.UTF8);
            }
        }
        /// <summary>
        ///  Get Unauthorized Result
        /// </summary>
        /// <returns>ApiErrorModel</returns>

        protected IActionResult GetUnauthorizedResult()
        {
            var response = new ApiErrorModel();

            response.Error.Code = HttpStatusCode.Unauthorized.ToString();
            return(StatusCode(StatusCodes.Status401Unauthorized, response));
        }
        public async Task <IActionResult> SigIn([FromBody] UserLoginInputModel inputModel)
        {
            var user = await this.userManager.Users.SingleOrDefaultAsync(u => u.UserName.Equals(inputModel.Username));

            var cansSignIn = user is not null && await this.signInManager.CanSignInAsync(user);

            var userSignInResult = await this.userManager.CheckPasswordAsync(user, inputModel.Password);

            if (user is null || !userSignInResult || !cansSignIn)
            {
                var error = new ApiErrorModel()
                {
                    Code        = nameof(user),
                    Description = ApiMessagesConstants.InvalidCredentials,
                };

                return(this.BadRequest(new List <ApiErrorModel> {
                    error
                }));
            }

            var roles = await this.userManager.GetRolesAsync(user);

            var response = this.mapper.Map <UserResponseModel>(user);

            response.Token = this.authService.GenerateJwt(user, roles);

            return(this.Ok(response));
        }
Exemple #13
0
        private async Task <ApiErrorModel> ExecuteHandlerTest(AuthorizationLevel authLevel, bool includeDetails)
        {
            var handler          = new ExceptionProcessingHandler(_config);
            var requestId        = Guid.NewGuid().ToString();
            var exception        = new Exception("TestException");
            var exceptionContext = new ExceptionContext(exception, ExceptionCatchBlocks.HttpServer)
            {
                Request = new HttpRequestMessage()
            };

            exceptionContext.Request.SetAuthorizationLevel(authLevel);
            exceptionContext.Request.SetConfiguration(_config);
            exceptionContext.Request.Properties.Add(ScriptConstants.AzureFunctionsRequestIdKey, requestId);
            exceptionContext.RequestContext = new System.Web.Http.Controllers.HttpRequestContext();

            var context = new ExceptionHandlerContext(exceptionContext);

            context.RequestContext.IncludeErrorDetail = includeDetails;

            handler.Handle(context);

            HttpResponseMessage response = await context.Result.ExecuteAsync(CancellationToken.None);

            ApiErrorModel error = await response.Content.ReadAsAsync <ApiErrorModel>();

            Assert.Equal(requestId, error.RequestId);

            return(error);
        }
        /// <summary>
        /// On action executing
        /// </summary>
        /// <param name="context">the context</param>
        /// <inheritdoc />
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!context.ModelState.IsValid)
            {
                var error = new ApiErrorModel();
                error.Code    = "BadArgument";
                error.Message = "Argumento invalido";

                foreach (var key in context.ModelState.Keys)
                {
                    var errorState = context.ModelState[key];

                    foreach (var detailError in errorState.Errors)
                    {
                        error.Details.Add(new ApiErrorModel()
                        {
                            Code    = "BadArgument",
                            Message = detailError.ErrorMessage,
                            Target  = key
                        });
                    }
                }

                context.Result = new BadRequestObjectResult(new BaseApiErrorModel()
                {
                    Error = error
                });
            }

            base.OnActionExecuting(context);
        }
        /// <summary>
        /// Get Server Error Result
        /// </summary>
        /// <param name="ex"></param>
        /// <returns>ApiErrorModel</returns>

        protected IActionResult GetServerErrorResult(string ex)
        {
            var response = new ApiErrorModel();

            response.Error.Code       = HttpStatusCode.InternalServerError.ToString();
            response.Error.Message    = ErrorMessageCode.SERVER_ERROR;
            response.Error.InnerError = ex;
            return(StatusCode(StatusCodes.Status500InternalServerError, response));
        }
        /// <summary>
        /// Get Not Found Result
        /// </summary>
        /// <param name="message"></param>
        /// <returns>ApiErrorModel</returns>
        protected IActionResult GetNotFoundResult(string message)
        {
            var response = new ApiErrorModel();

            response.Error.Code    = HttpStatusCode.BadRequest.ToString();
            response.Error.Message = message;

            return(NotFound(response));
        }
        /// <summary>
        ///  Get Forbidden Error Result
        /// </summary>
        /// <returns>ApiErrorModel</returns>
        protected IActionResult GetForbiddenErrorResult()
        {
            var response = new ApiErrorModel();

            response.Error.Code       = HttpStatusCode.Forbidden.ToString();
            response.Error.Message    = ErrorMessageCode.AUTH_FORBIDDEN_ERROR;
            response.Error.InnerError = "";
            return(StatusCode(StatusCodes.Status403Forbidden, response));
        }
Exemple #18
0
        private void TraceErrorEvent(ExceptionContext exceptionContext, ApiErrorModel error)
        {
            string controllerName = exceptionContext.ControllerContext?.ControllerDescriptor.ControllerName ?? "<unknown>";
            string actionName     = exceptionContext.ActionContext?.ActionDescriptor.ActionName ?? "<unknown>";

            string message    = JsonConvert.SerializeObject(error);
            var    traceEvent = new TraceEvent(TraceLevel.Error, message, $"ApiError.{controllerName}.{actionName}", exceptionContext.Exception);

            _traceWriterLoader.Value.Trace(traceEvent);
        }
Exemple #19
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <typeparam name="T">The type</typeparam>
        /// <param name="ex">The ex.</param>
        /// <param name="message">The message.</param>
        /// <returns>the action</returns>
        protected IActionResult BadRequest <T>(CoreException <T> ex, string message = null)
        {
            var error = new ApiErrorModel();

            error.Code    = ex.Code.ToString();
            error.Message = message ?? ex.Message;
            error.Target  = ex.Target;
            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = error
            }));
        }
Exemple #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            ApiErrorModel apiErrorModel = null;


            if (context.Exception is ApiException)
            {
                var ex = context.Exception as ApiException;

                apiErrorModel = new ApiErrorModel(ex.Message)
                {
                    Errors = ex.Errors,
                };
                context.HttpContext.Response.StatusCode = ex.StatusCode;
            }
            else if (context.Exception is DomainException || context.Exception is ApplicationException)
            {
                apiErrorModel = new ApiErrorModel(context.Exception.Message);

                context.HttpContext.Response.StatusCode = 403;
            }
            else if (context.Exception is UnauthorizedAccessException)
            {
                apiErrorModel = new ApiErrorModel("Unauthorized Access");

                context.HttpContext.Response.StatusCode = 401;
            }
            else
            {
#if !DEBUG
                var    msg   = "An unhandled error occurred.";
                string stack = null;
#else
                var    msg   = context.Exception.GetBaseException().Message;
                string stack = context.Exception.StackTrace;
#endif
                apiErrorModel = new ApiErrorModel(msg)
                {
                    Detail = stack,
                };

                context.HttpContext.Response.StatusCode = 500;
            }

            //Set Exception Type
            apiErrorModel.Type = context?.Exception?.GetType().Name;

            context.Result = new JsonResult(apiErrorModel);

            Log.Error(context.Exception, "");

            base.OnException(context);
        }
Exemple #21
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <typeparam name="T">Exception type</typeparam>
        /// <param name="code">The code.</param>
        /// <param name="error">The error.</param>
        /// <returns>the action</returns>
        protected IActionResult BadRequest <T>(T code, string error)
        {
            var apiError = new ApiErrorModel()
            {
                Code    = code.ToString(),
                Message = this.messageExceptionFinder.GetErrorMessage(code),
                Target  = null
            };

            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = apiError
            }));
        }
Exemple #22
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <typeparam name="T">Exception type</typeparam>
        /// <param name="code">The code.</param>
        /// <param name="errors">The errors.</param>
        /// <param name="target">The target.</param>
        /// <returns>the action</returns>
        protected IActionResult BadRequest <T>(CoreException <T> code, IList <ApiErrorModel> errors, string target = null)
        {
            var error = new ApiErrorModel()
            {
                Code    = code.ToString(),
                Message = this.messageExceptionFinder.GetErrorMessage(code),
                Target  = target,
                Details = errors == null || errors.Count == 0 ? null : errors
            };

            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = error
            }));
        }
        public override void Handle(ExceptionHandlerContext context)
        {
            var error = new ApiErrorModel(HttpStatusCode.InternalServerError);

            AuthorizationLevel currentLevel = context.Request.GetAuthorizationLevel();

            foreach (var handler in GetExceptionHandlers(context.Exception))
            {
                handler(context.ExceptionContext, currentLevel, error);
            }

            TraceErrorEvent(context.ExceptionContext, error);

            context.Result = new ResponseMessageResult(context.Request.CreateResponse(error.StatusCode, error));
        }
Exemple #24
0
        /// <summary>
        /// A bad request response.
        /// </summary>
        /// <param name="errors">The errors.</param>
        /// <param name="target">The target.</param>
        /// <returns>the action result</returns>
        protected IActionResult BadRequest(IList <ApiErrorModel> errors, string target = null)
        {
            var error = new ApiErrorModel()
            {
                Code    = "BadArgument",
                Message = "BadArgument",
                Target  = target,
                Details = errors == null || errors.Count == 0 ? null : errors
            };

            return(this.StatusCode(400, new BaseApiErrorModel()
            {
                Error = error
            }));
        }
Exemple #25
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            string version  = (string)context.ActionArguments["version"];
            string filename = (string)context.ActionArguments["filename"];
            string branch   = (string)context.ActionArguments["branch"];

            var notValid = new ApiErrorModel();

            if (filename == null)
            {
                notValid.code    = "InvalidFilename";
                notValid.message = "Invalid File name";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }

            if (!ValidVersion.ValidSemver(version))
            {
                notValid.code    = "NotValidVersion";
                notValid.message = "The version in the path isn't valid";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }

            var upwardDb = (upwardContext)context.HttpContext.RequestServices.GetService(typeof(upwardContext));
            var Id       = context.HttpContext.Response.Headers["X-Project-Id"];

            var ver = version.Split(".");

            int major = int.Parse(ver[0]);
            int minor = int.Parse(ver[1]);
            int patch = int.Parse(ver[2]);


            var doesExists = upwardDb.Pkgfile
                             .Any(r => r.Project.ToString() == Id.ToString() && r.Major == major && r.Minor == minor && r.Patch == patch && r.Branch == branch && r.Filename.Contains(filename));

            if (!doesExists)
            {
                notValid.code    = "NoSuchPackage";
                notValid.message = "No package with that version or filename exists";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }
        }
 /// <summary>
 /// 自定义
 /// </summary>
 /// <param name="statusCode"></param>
 /// <param name="code"></param>
 /// <param name="message"></param>
 /// <returns></returns>
 private HttpResponseMessage GetResponseMessage(HttpStatusCode statusCode, int code, string message)
 {
       //实例化错误消息
       var resultModel = new ApiErrorModel()
       {
             StatusCode = statusCode,
             Code = code,
             Message = message
       };
       //创建有关错误消息的httpresponse
       return new HttpResponseMessage()
       {
             StatusCode = statusCode,
             Content = new ObjectContent<ApiErrorModel>(resultModel, new JsonMediaTypeFormatter(), "application/json")
       };
 }
Exemple #27
0
        public async Task <IActionResult> Create([FromBody] CreateModel create)
        {
            var projectName = HttpContext.Request.Host.ToString().Split(".")[0];
            var project     = accountsDb.Project.Where(r => r.Name == projectName).FirstOrDefault();

            var hasNoRollback = await ValidVersion.NoRollback(create.Version, create.Branch, project.Id, upwardDb);

            var apiError = new ApiErrorModel();

            if (!hasNoRollback)
            {
                apiError.code    = "VersionHasRollback";
                apiError.message = "The version specified in the header has a rollback";

                HttpContext.Response.StatusCode = 400;
                return(Json(apiError));
            }

            var ver         = create.Version.Split(".");
            var currentDate = DateTime.Now;

            var newPackage = new Pkgfile
            {
                Project  = project.Id,
                Major    = int.Parse(ver[0]),
                Minor    = int.Parse(ver[1]),
                Patch    = int.Parse(ver[2]),
                Branch   = create.Branch,
                Filename = new string[] { },
                Created  = currentDate
            };

            await upwardDb.Pkgfile.AddAsync(newPackage);

            await upwardDb.SaveChangesAsync();

            var SuccessResponse = new CreateSuccessModel
            {
                Url     = $"{HttpContext.Request.Host.ToString()}/{create.Branch}/{create.Version}/",
                Created = currentDate.ToString(),
                Branch  = create.Branch,
                Version = create.Version
            };

            return(Json(SuccessResponse));
        }
Exemple #28
0
        /// <summary>
        /// Gets the HTTP response message with an API error model.
        /// </summary>
        /// <param name="ex">The exception.</param>
        /// <returns>A HTTP response message.</returns>
        public HttpResponseMessage GetHttpResponseMessage(Exception ex)
        {
            // Creates error model from exception.
            var statusCode = GetHttpStatusCode(ex);

            // Hides real reason when HTTP status code is 500.
            var apiErrorModel = new ApiErrorModel {
                Message = ex.Message
            };

            // Creates response message with API error model.
            var result = new HttpResponseMessage(statusCode);

            result.Content = new ObjectContent <ApiErrorModel>(
                apiErrorModel, new JsonMediaTypeFormatter(), "application/json");

            return(result);
        }
        public override void OnException(ExceptionContext context)
        {
            ApiErrorModel apiError;

            if (context.Exception is ValidationException vex)
            {
                apiError = vex.Errors.Any()
                    ? new ApiErrorModel
                {
                    Errors = vex.Errors
                             .Select(x => new PropertyErrorModel
                    {
                        Name    = x.PropertyName,
                        Message = x.ErrorMessage
                    })
                             .ToList()
                }
                    : new ApiErrorModel {
                    Error = vex.Message
                };

                context.HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
            else if (context.Exception is AuthenticationException aex)
            {
                apiError = new ApiErrorModel {
                    Error = aex.Message
                };
                context.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
            }
            else
            {
                context.HttpContext.Response.StatusCode = StatusCodes.Status500InternalServerError;
                apiError = new ApiErrorModel {
                    Error = "Internal Server Error"
                };

                // TODO: Log error
            }

            context.Result = new JsonResult(apiError);

            base.OnException(context);
        }
Exemple #30
0
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            CreateModel create = (CreateModel)context.ActionArguments["create"];

            var notValid = new ApiErrorModel();

            if (string.IsNullOrWhiteSpace(create.Version))
            {
                notValid.code    = "NoVersion";
                notValid.message = "There is no version in the body";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }

            if (!ValidVersion.ValidSemver(create.Version))
            {
                notValid.code    = "NotValidVersion";
                notValid.message = "The version in the body is not valid";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }

            if (string.IsNullOrWhiteSpace(create.Branch))
            {
                notValid.code    = "EmptyBranch";
                notValid.message = "The branch name is empty or consist of whitespace(s)";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }

            if ((string)context.HttpContext.Request.Headers["content-type"] == null)
            {
                notValid.code    = "NoContentType";
                notValid.message = "Missing Content-Type in header";
                context.HttpContext.Response.StatusCode = 400;
                context.Result = new JsonResult(notValid);
                return;
            }
        }