Пример #1
0
        public async Task <IHttpActionResult> UpdateCaseAsync(int id, CaseInfo json)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的案例");
            }
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            var cases = await this.m_CaseInfoStorage.GetAsync(id);

            if (cases == null)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "更新的案例不存在");
            }

            cases.title      = json.title;
            cases.imgurl     = json.imgurl;
            cases.typeid     = json.typeid;
            cases.link       = json.link;
            cases.seecount   = json.seecount;
            cases.prizecount = json.prizecount;
            cases.sort       = json.sort;

            ValidatorProvider.ThrowIfInValidate <CaseInfoValidator, CaseInfo>(cases);
            int count = await this.m_CaseInfoStorage.UpdateAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "更新失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #2
0
        public async Task <IHttpActionResult> GetArticleAsync(int id)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要获取的资讯");
            }
            var article = await this.m_ArticleStorage.GetAsync(id);

            if (article == null)
            {
                throw new BadRequestException(ResultCode.ActionFail, "指定获取的资讯不存在");
            }

            var data = new
            {
                article.id,
                article.imgurl,
                fullimgurl = WebConfigs.UrlPrefix + article.imgurl,
                article.title,
                article.sort,
                article.author,
                article.seecount,
                article.samllcontents,
                article.contents,
                article.ishot,
                article.isnew,
                article.isshow,
                article.typeid,
                article.typetext,
                article.created
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #3
0
        public async Task <IHttpActionResult> GetCaseListAsync(int page, int pageSize, string title = "", int type = 0, string orderBy = "")
        {
            var pageList = await this.m_CaseInfoStorage.GetPagedListAsync(page, pageSize, title ?? "", type, orderBy);

            var data = new
            {
                list = pageList.RowSet.Select(i => new
                {
                    i.id,
                    i.imgurl,
                    fullimgurl = WebConfigs.UrlPrefix + i.imgurl,
                    i.title,
                    i.sort,
                    i.link,
                    i.seecount,
                    i.prizecount,
                    i.created,
                    i.typeid,
                    i.typetext
                }),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #4
0
        public async Task <IHttpActionResult> UpdateBannerAsync(int id, Banner json)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的Banner");
            }
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            var banner = await this.m_BannerStorage.GetAsync(id);

            if (banner == null)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "更新的案例不存在");
            }

            banner.title     = json.title;
            banner.image_url = json.image_url;
            banner.type      = json.type;
            banner.link_url  = json.link_url;
            banner.sort      = json.sort;

            ValidatorProvider.ThrowIfInValidate <BannerValidator, Banner>(banner);
            int count = await this.m_BannerStorage.UpdateAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "更新失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #5
0
        public async Task <IHttpActionResult> GetArticleListAsync(int page, int pageSize, string title = "", int type = 0, int ishot = -1, int isnew = -1, int isshow = -1, string orderBy = "")
        {
            var pageList = await this.m_ArticleStorage.GetPagedListAsync(page, pageSize, title ?? "", type, ishot, isnew, isshow, orderBy);

            var data = new
            {
                list = pageList.RowSet.Select(i => new
                {
                    i.id,
                    i.imgurl,
                    fullimgurl = WebConfigs.UrlPrefix + i.imgurl,
                    i.title,
                    i.sort,
                    i.author,
                    i.seecount,
                    i.samllcontents,
                    i.contents,
                    i.ishot,
                    i.isnew,
                    i.isshow,
                    i.typeid,
                    i.typetext,
                    i.created
                }),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #6
0
        public async Task <IHttpActionResult> GetTypeListAsync(int parentid)
        {
            var list = await this.m_TypeInfoStorage.GetListAsync(parentid);

            var data = list.Where(i => i.parentid == parentid);

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #7
0
        public async Task <ActionResult> LoginAsync(Login json)
        {
            // 判断是否使用新登录页面
            if (WebConfigs.UseNewUserbackstage)
            {
                return(HttpNotFound());
            }

            var result = new JsonApiResult <string> {
                data = ""
            };

            try
            {
                if (json == null)
                {
                    throw new ArgumentException("请输入用户名");
                }
                if (string.IsNullOrEmpty(json.username))
                {
                    throw new ArgumentException("用户名不能为空");
                }
                if (string.IsNullOrEmpty(json.password))
                {
                    throw new ArgumentException("密码不能为空");
                }
                if (string.IsNullOrEmpty(json.vcode) || !json.vcode.Equals(Session["vcode"]))
                {
                    throw new ArgumentException("验证码错误");
                }

                //移除验证码
                Session.Remove("vcode");

                var cookie = await ApiProvider.LoginAsync(json.username, json.password);

                if (!cookie.success)
                {
                    result.code = cookie.code;
                    result.msg  = cookie.msg;
                }
                else
                {
                    //写入cookie
                    Response.Cookies.Add(ApiProvider.GetWriteCookie(cookie.data));
                    result.code = cookie.code;
                }
            }
            catch (ArgumentException e)
            {
                result.code = -1;
                result.msg  = e.Message;
            }

            return(Json(result));
        }
Пример #8
0
        public override Task OnExceptionAsync(HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken)
        {
            var    exception = actionExecutedContext.Exception;
            bool   process   = false;
            int    code      = 0;
            string message   = "";

            if (exception is HttpResponseException)
            {
                process = true;
                actionExecutedContext.Response = (exception as HttpResponseException).Response;
            }
            else if (exception is ArgumentException)
            {
                code    = ResultCode.ArgumentException;
                message = exception.Message;
            }
            else if (exception is BadRequestException)
            {
                var ex = exception as BadRequestException;
                code    = ex.ErrorCode;
                message = ex.Message ?? "";
            }
            else
            {
                code = ResultCode.SystemException;
#if DEBUG
                message = exception.ToString();
#else
                message = "系统出错,请稍后再试~";
                //记录未处理异常
                LogProvider.Error.Error(exception);
#endif
            }

            if (!process)
            {
                var data = new JsonApiResult
                {
                    code = code,
                    msg  = message
                };
                //判断是否文件Action
                if (actionExecutedContext.ActionContext.ActionDescriptor.GetCustomAttributes <FileResultAttribute>().Any())
                {
                    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.BadRequest, data);
                }
                else
                {
                    actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(HttpStatusCode.OK, data);
                }
            }

            return(base.OnExceptionAsync(actionExecutedContext, cancellationToken));
        }
Пример #9
0
 private static void ConfigureStatusCodePagesHandler(IApplicationBuilder app)
 {
     app.UseStatusCodePages(errApp =>
     {
         errApp.Run(async context =>
         {
             await JsonApiResult.Error($"Error: {(HttpStatusCode)context.Response.StatusCode}", context.Response.StatusCode)
             .ExecuteResultAsync(context);
         });
     });
 }
Пример #10
0
        public async Task <IHttpActionResult> UploadEditorImageAsync()
        {
            object data    = null;
            string tempDir = HttpContext.Current.Server.MapPath("~/temp");

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            string dateStr = DateTime.Now.ToString("yyyy-MM-dd");
            string dstDir  = HttpContext.Current.Server.MapPath("~/upload/file/editor/image/") + dateStr + "/";

            if (!Directory.Exists(dstDir))
            {
                Directory.CreateDirectory(dstDir);
            }

            var fileProvider = new MultipartFormDataStreamProvider(tempDir);
            var multipart    = await Request.Content.ReadAsMultipartAsync(fileProvider);

            try
            {
                ValidatorProvider.ThrowIfEqual(multipart.FileData.Count, 0, "请选择上传的文件");

                var      fileData = multipart.FileData[0];
                var      fileName = fileData.Headers.ContentDisposition.FileName.Replace("\"", "").Replace("\"", "");
                var      ext      = Path.GetExtension(fileName).ToLower();
                string[] picExts  = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
                ValidatorProvider.ThrowIfNotIn(ext, picExts, "上传的图片格式不正确");
                var fi = new FileInfo(fileData.LocalFileName);
                ValidatorProvider.ThrowIfMoreThan((int)fi.Length, 5 * 1024 * 1024, "上传的图片不能大于5M");

                string file = Guid.NewGuid().ToString("N") + ext;
                File.Move(fileData.LocalFileName, Path.Combine(dstDir, file));
                var uri = Request.RequestUri;
                data = new
                {
                    url     = $"/upload/file/editor/image/{dateStr}/{file}",
                    fullurl = $"{WebConfigs.UrlPrefix}upload/file/editor/image/{dateStr}/{file}"
                };
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                Request.RemoveTempFile(multipart.FileData);
            }

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #11
0
        public async Task <IHttpActionResult> GetCaseListAsync(int page, int pageSize, int typeid = 0, string title = "")
        {
            var pageList = await this.m_CaseInfoStorage.GetPagedListAsync(page, pageSize, title ?? "", typeid, "");

            var data = new
            {
                list  = pageList.RowSet.Select(i => Projections.GetCaseProjection(i)),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #12
0
        public async Task <IHttpActionResult> GetArticleListAsync(int page, int pageSize, int typeid = 0, int ishot = -1)
        {
            var pageList = await this.m_ArticleStorage.GetPagedListAsync(page, pageSize, "", typeid, ishot, -1, -1, "created_DESC");

            var data = new
            {
                list  = pageList.RowSet.Select(i => Projections.GetArticleProjection(i)),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #13
0
        public async Task <IHttpActionResult> DeleteArticleAsync(int id)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要删除的资讯");
            }
            int count = await this.m_ArticleStorage.DeleteAsync(id);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "删除失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #14
0
        public async Task <IHttpActionResult> AddCaseAsync(CaseInfo json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            ValidatorProvider.ThrowIfInValidate <CaseInfoValidator, CaseInfo>(json);
            int count = await this.m_CaseInfoStorage.InsertAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "添加失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #15
0
        public async Task <IHttpActionResult> LoginAsync(User json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            string vcode = "";

            if (!CacheProvider.TryGet("vcode." + json.sid, out vcode) || vcode != json.vcode)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "验证码错误");
            }
            if (string.IsNullOrEmpty(json.username))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "登录用户名不能为空");
            }
            if (string.IsNullOrEmpty(json.password))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "登录密码不能为空");
            }

            string password = HashAlgorithmProvider.ComputeHash("MD5", json.password, true);
            var    user     = await this.m_UserStorage.GetAsync(json.username);

            if (user == null || user.password != password)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "用户名或密码错误");
            }
            if (user.status != 1)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "用户已禁用,请联系管理员");
            }

            //remove validate code
            CacheProvider.Remove("vcode." + json.sid);

            var data = new
            {
                user.username,
                user.nickname,
                access_token = JweProvider.Encode(JwtCommon.SignKey, user.id, JwtCommon.ExpireInMinutes),
                expires      = DateTimeUtil.GetTimestamp(DateTime.Now.AddHours(2))
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #16
0
        public async Task <IHttpActionResult> AddArticleAsync(Article json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            ValidatorProvider.ThrowIfInValidate <ArticleValidator, Article>(json);

            json.created = json.created.ToLocalTime();
            int count = await this.m_ArticleStorage.InsertAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "添加失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #17
0
        public async Task <IHttpActionResult> GetCommentListAsync(int page, int pageSize, string created = "", string orderBy = "")
        {
            var pageList = await this.m_CommentStorage.GetPagedListAsync(page, pageSize, "", created ?? "", orderBy);

            var data = new
            {
                list = pageList.RowSet.Select(i => new
                {
                    i.id,
                    i.contents,
                    i.ipaddress,
                    i.created
                }),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #18
0
        public async Task <IHttpActionResult> AddCommenttAsync(Comment json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            //获取ip地址
            json.ipaddress = Request.GetUserHostAddress();
            ValidatorProvider.ThrowIfInValidate <CommentValidator, Comment>(json);
            int count = await this.m_CommentStorage.InsertAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "添加失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #19
0
        private static void ConfigureExceptionHandler(IApplicationBuilder app)
        {
            app.UseExceptionHandler(appError =>
            {
                appError.Run(async context =>
                {
                    var contextFeature = context.Features.Get <IExceptionHandlerFeature>();

                    if (contextFeature != null)
                    {
                        var exception = contextFeature.Error;

                        await JsonApiResult.Error($"ОШИБКА: {exception?.InnerException?.Message ?? exception?.Message}", 500).ExecuteResultAsync(context);
                    }
                    else
                    {
                        await JsonApiResult.Error("Internal server error.", 500).ExecuteResultAsync(context);
                    }
                });
            });
        }
Пример #20
0
        public async Task <IHttpActionResult> UpdateArticleAsync(int id, Article json)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的资讯");
            }
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            var cases = await this.m_ArticleStorage.GetAsync(id);

            if (cases == null)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "更新的资讯不存在");
            }

            cases.title         = json.title;
            cases.author        = json.author;
            cases.imgurl        = json.imgurl;
            cases.typeid        = json.typeid;
            cases.samllcontents = json.samllcontents;
            cases.seecount      = json.seecount;
            cases.contents      = json.contents;
            cases.sort          = json.sort;
            cases.ishot         = json.ishot;
            cases.isnew         = json.isnew;
            cases.isshow        = json.isshow;
            cases.created       = json.created.ToLocalTime();

            ValidatorProvider.ThrowIfInValidate <ArticleValidator, Article>(json);
            int count = await this.m_ArticleStorage.UpdateAsync(json);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "更新失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #21
0
        public async Task <IHttpActionResult> UpdatePasswordAsync(User json)
        {
            if (json == null)
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
            if (string.IsNullOrEmpty(json.password))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "旧密码不能为空");
            }
            if (string.IsNullOrEmpty(json.newpassword))
            {
                throw new BadRequestException(ResultCode.ArgumentException, "新密码不能为空");
            }
            if (json.newpassword.Length > 18 || json.newpassword.Length < 5)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "新密码长度为5~18位");
            }

            string oldpassword = HashAlgorithmProvider.ComputeHash("MD5", json.password, true);
            var    user        = Request.GetProperty <User>(HttpPropertyKeys.AuthorizedUser);

            if (user.password != oldpassword)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "旧密码不正确");
            }

            string newpassword = HashAlgorithmProvider.ComputeHash("MD5", json.newpassword, true);

            user.password = newpassword;
            int count = await this.m_UserStorage.UpdateAsync(user);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "更新密码失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #22
0
        public async Task <IHttpActionResult> GetIntentionListAsync(int page, int pageSize, string keyword = "", string intention = "", string orderBy = "")
        {
            var intentions = StringProvider.SpiltToNumbers <int>(",", intention);
            var pageList   = await this.m_IntentionStorage.GetPagedListAsync(page, pageSize, keyword ?? "", intentions, orderBy);

            var data = new
            {
                list = pageList.RowSet.Select(i => new
                {
                    i.id,
                    i.name,
                    i.phone,
                    i.intention,
                    i.useragent,
                    i.remark,
                    intention_text = GetIntentionText(i.intention),
                    i.created
                }),
                count = pageList.Count
            };

            return(Json(JsonApiResult.Ok(data)));
        }
Пример #23
0
        public async Task <IHttpActionResult> SetCaseSeeCountAsync(int id)
        {
            if (id <= 0)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "请选择要更新的案例");
            }
            var cases = await this.m_CaseInfoStorage.GetAsync(id);

            if (cases == null)
            {
                throw new BadRequestException(ResultCode.ArgumentException, "更新的案例不存在");
            }

            cases.seecount++;
            int count = await this.m_CaseInfoStorage.UpdateAsync(cases);

            if (count <= 0)
            {
                throw new BadRequestException(ResultCode.ActionFail, "操作失败");
            }

            return(Json(JsonApiResult.Ok("")));
        }
Пример #24
0
        public async Task <IHttpActionResult> GetTypeListAsync(int parentid)
        {
            var list = await this.m_TypeInfoStorage.GetListAsync(parentid);

            return(Json(JsonApiResult.Ok(list)));
        }
Пример #25
0
        public JsonApiResult LastFileData()
        {
            var report = _sqlRepository.LastReport();

            return(JsonApiResult.Success(report));
        }
Пример #26
0
 static JsonApiResult ErrorInvalidInput(ModelStateDictionary model)
 {
     return(JsonApiResult.Error($@"Некорректное тело запроса. Ошибки: {string.Join(", ", GetErrorList(model))}", 415));
 }