public async Task <ApiResult <LoginResult> > UserLogin([FromBody] UserLoginInfo loginInfo) { var result = new ApiResult <LoginResult>().Success(); _logger.Info("test"); if (loginInfo == null) { return(result.Error("无效的登录信息")); } try { var user = await _repository.FirstOrDefaultAsync(x => x.UserName == loginInfo.LoginName && x.WebSiteId == loginInfo.WebSiteId); if (user == null) { return(result.Error("账号不存在")); } if (user.Password != Encryptor.MD5Entry(loginInfo.Password)) { return(result.Error("账号或密码错误")); } var claims = new List <Claim> { new Claim(ClaimConst.WebSiteId, user.WebSiteId), new Claim(ClaimConst.UserId, user.Id), new Claim(ClaimConst.UserName, user.UserName), new Claim(JwtRegisteredClaimNames.Sub, "CXY.CJS"), new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString("N")) }; var token = _jwtTokenProvider.GenerateJwtToken(claims); result.Data = new LoginResult { Token = token, Expired = _jwtBearerConfig.ValidMinutes * 60 }; } catch (EntityNotFoundException) { result.Code = 0; result.Message = "账号或密码错误"; } catch (Exception ex) { result.Error(ex.Message); } return(result); }
public void Command(RouteData data) { if (!ZeroApplication.ZerCenterIsRun) { _result = ApiResult.Error(ErrorCode.NoReady); return; } _data = data; _words = data.ApiName.Split(new[] { '/', '\\' }, StringSplitOptions.RemoveEmptyEntries); if (_words.Length == 0) { data.Status = RouteStatus.FormalError; data.ResultMessage = ApiResult.ArgumentErrorJson; return; } switch (_words[0].ToLower()) { case "install": Install(); break; default: Call(); break; } _data.ResultMessage = JsonConvert.SerializeObject(_result); }
public ApiResult FlushList() { var result = CallCommand("list"); if (result.State != ZeroOperatorStateType.Ok) { return(ApiResult.Error(ErrorCode.NetworkError, "参数错误")); } if (!result.TryGetValue(ZeroFrameType.Status, out var json)) { ZeroTrace.WriteError("FlushList", "Empty"); return(ApiResult.Error(ErrorCode.LogicalError, "空数据")); } try { var list = JsonConvert.DeserializeObject <List <ZeroPlan> >(json); foreach (var plan in list) { SyncPlan(plan); } return(ApiResult.Succees()); } catch (Exception ex) { ZeroTrace.WriteException("FlushList", ex, json); return(ApiResult.Error(ErrorCode.LocalException, "内部服务")); } }
public static ApiResult Update(StationConfig option) { if (!ZeroApplication.Config.TryGetConfig(option.Name, out var config)) { return(ApiResult.Error(ErrorCode.NetworkError, "站点不存在")); } try { var result = SystemManager.Instance.CallCommand("update", JsonConvert.SerializeObject(option)); if (!result.InteractiveSuccess) { return(ApiResult.Error(ErrorCode.NetworkError, "服务器无法访问")); } switch (result.State) { case ZeroOperatorStateType.Ok: var apiResult = ApiResult.Succees(); apiResult.Status = new ApiStatusResult { ErrorCode = ErrorCode.Success, ClientMessage = "安装成功" }; return(apiResult); default: return(ApiResult.Error(ErrorCode.LogicalError, result.State.Text())); } } catch (Exception e) { return(ApiResult.Error(ErrorCode.NetworkError, e.Message)); } }
public async Task <ApiResult> GetToken() { Request.Headers.TryGetValue("client_id", out StringValues clientId); Request.Headers.TryGetValue("client_secret", out StringValues clientSecret); HttpClient httpClient = _httpClientFactory.CreateClient(); Dictionary <string, string> headers = new Dictionary <string, string>(); headers.Add("client_id", clientId); headers.Add("client_secret", clientSecret); headers.Add("grant_type", "client_credentials"); FormUrlEncodedContent content = new FormUrlEncodedContent(headers); var response = await httpClient.PostAsync("http://localhost:5003/connect/token", content); if (!response.IsSuccessStatusCode) { return(ApiResult.Error(HttpStatusCode.BAD_REQUEST, response.StatusCode.GetEnumText())); } var responseString = await response.Content.ReadAsStringAsync(); dynamic result = JsonConvert.DeserializeObject <dynamic>(responseString); int expires = result.expires_in; int minutes = new TimeSpan(0, 0, expires).Minutes; string token = result.access_token; JwtToken jwtToken = new JwtToken(token, minutes, DateTime.Now); return(ApiResult.Success(jwtToken)); }
public Task <ApiResult <SysUserDto> > GetModelAsync(long id) { IQueryable <SysUser> sysUserQueryable = _sysUserRepository.GetAll(); IQueryable <SysUserGroup> sysUserGroupQueryable = _sysUserGroupRepository.GetAll(); IQueryable <SysGroup> sysGroupQueryable = _sysGroupRepository.GetAll(); var userModel = from u in sysUserQueryable join uug in sysUserGroupQueryable on u.ID equals uug.UserID into uuug from uuugModel in uuug.DefaultIfEmpty() join ug in sysGroupQueryable on uuugModel.GroupID equals ug.ID into uug from uugModel in uug.DefaultIfEmpty() where u.ID == id select new SysUserDto() { LoginName = u.LoginName, DepartmentID = u.DepartmentID, NiceName = u.NiceName, ContractPhone = u.ContractPhone, GroupName = uugModel.GroupName }; SysUserDto sysUserDto = userModel.FirstOrDefault(); if (sysUserDto != null) { return(Task.FromResult(ApiResult <SysUserDto> .Ok(sysUserDto))); } return(Task.FromResult(ApiResult <SysUserDto> .Error())); }
public async Task <ApiResult <T> > GetAsync <T>(string url, bool authed = true) { using (var client = new HttpClient()) { try { if (authed) { Authed(client); } using (var response = await client.GetAsync(url)) { if (response.IsSuccessStatusCode) { var str = await response.Content.ReadAsStringAsync(); return(JsonUtils.Deserialize <T>(str)); } return(ApiResult <T> .Error(response.ReasonPhrase)); } } catch (Exception ex) { return(ApiResult <T> .Error(ex)); } } }
/// <summary> /// 重载 /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> protected override Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { Request = request; int code = Check(); //校验不通过,直接返回,不做任何处理 if (code != 0) { LogRecorder.FlushMonitor("Authorization头校验出错"); return(Task.Factory.StartNew(() => { var result = ApiResult.Error(code); return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(result)) }; }, cancellationToken)); } //正常结束时清理调用上下文 var resultTask = base.SendAsync(request, cancellationToken); resultTask.ContinueWith((task, state) => { CallContext.LogicalSetData("ApiContext", null); }, null, cancellationToken); return(resultTask); }
public static async Task <ApiResult <string> > Add(Token token, BookmarksModel model) { //var result=null; try { string url = string.Format(Constact.BookMarks_add); Dictionary <string, string> _params = new Dictionary <string, string>(); _params.Add("LinkUrl", model.LinkUrl); _params.Add("Title", model.Title); _params.Add("Summary", model.Summary); _params.Add("Tags", model.Tag); var result = await HttpBase.PostAsync(token, url, _params); if (result.IsSuccess) { return(ApiResult.Ok(result.Message)); //return ApiResult.Ok(list); } return(ApiResult <string> .Error(result.Message)); //return ApiResult<List<Article>>.Error(result.Message); } catch (Exception ex) { return(ApiResult <string> .Error(ex.Message)); } }
/// <summary> /// 验证码发送记录入库 /// </summary> /// <param name="sendResult">验证码发送结果</param> /// <param name="sendBody">发送的内容</param> /// <param name="guid">唯一标识</param> /// <param name="mobile">手机号</param> /// <param name="code">验证码</param> /// <returns></returns> private async Task <ApiResult> SaveSendHistoryAsync(ApiResult sendResult, string sendBody, string guid, string mobile, string code) { if (sendResult.code != ApiCode.成功) { return(ApiResult.Error(sendResult.msg)); } //用于校验验证码是否正确 await _cacheServices.AddAsync(guid, code, 60 * 10); //用于校验是否发送频繁 await _cacheServices.AddAsync(mobile, DateTime.Now.ToTimeStamp(), 60); _logger.LogDebug($"【发送验证码】内容:{sendBody},GUID:{guid},手机号:{mobile},验证码:{code},返回结果:{JsonHelper.Serialize(sendResult)}"); //保存到数据库中 await _validateCodeHistoryServices.InsertAsync(new Model.Entity.ValidateCodeHistory() { Address = mobile, Body = sendBody, IsSendOK = sendResult.code == ApiCode.成功, Result = JsonHelper.Serialize(sendResult), UUID = guid, Type = Model.Entity.SMSType.CellPhone, }); return(ApiResult.OK()); }
/// <summary> /// 通过Post调用 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="apiName"></param> /// <param name="form"></param> /// <returns></returns> public ApiResult <TResult> Post <TResult>(string apiName, string form) { LogRecorder.BeginStepMonitor("内部API调用" + ToUrl(apiName)); string ctx = string.IsNullOrEmpty(Bearer) ? null : $"Bearer {Bearer}"; LogRecorder.MonitorTrace(ctx); LogRecorder.MonitorTrace("Arguments:" + form); HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ToUrl(apiName)); req.Method = "POST"; req.ContentType = "application/x-www-form-urlencoded"; req.Headers.Add(HttpRequestHeader.Authorization, ctx); try { using (Stream rs = req.GetRequestStream()) { byte[] formData = Encoding.UTF8.GetBytes(form); rs.Write(formData, 0, formData.Length); } } catch (Exception ex) { LogRecorder.Exception(ex); LogRecorder.EndStepMonitor(); return(ApiResult.Error <TResult>(ErrorCode.RemoteError)); } return(GetResult <TResult>(req)); }
/// <summary> ///根据id获取问答详情 /// </summary> /// <param name="token"></param> /// <param name="id"></param> /// <returns></returns> public static async Task <ApiResult <QuestionModel> > GetQuestionDetail(Token token, int id) { try { string url = string.Format(Constact.QuestionDetail, id); var result = await HttpBase.GetAsync(url, null, token); if (result.IsSuccess) { var articleDetail = JsonConvert.DeserializeObject <QuestionModel>(result.Message); //successAction(list); return(ApiResult.Ok(articleDetail)); } else { return(ApiResult <QuestionModel> .Error(result.Message)); //errorAction(result.Message); } } catch (Exception ex) { //errorAction(ex.StackTrace.ToString()); return(ApiResult <QuestionModel> .Error(ex.Message)); } }
public static async Task <ApiResult <List <Article> > > ListArticle(Token token, int pageIndex, int position) { try { string url = string.Empty; if (position == 0) { url = string.Format(Constact.SiteHomeArticleList, pageIndex, 10); } else { url = string.Format(Constact.ArticleHot, pageIndex, 10); } var result = await HttpBase.GetAsync(url, null, token); if (result.IsSuccess) { var list = JsonConvert.DeserializeObject <List <Article> >(result.Message); //successAction(list); return(ApiResult.Ok(list)); } else { return(ApiResult <List <Article> > .Error(result.Message)); //errorAction(result.Message); } } catch (Exception ex) { //errorAction(ex.StackTrace.ToString()); return(ApiResult <List <Article> > .Error(ex.Message)); } }
public void OnException(ExceptionContext context) { //已处理 if (context.ExceptionHandled) { return; } if (context.Exception.GetType().Equals(typeof(CustomException))) { //只有指定了InnerException的才会记录,不然Seq里太多异常日志了,不方便排查关键性问题 if (context.Exception.InnerException != null) { _logger.LogError(context.Exception.InnerException, "发生异常(手动)"); } } else { _logger.LogError(context.Exception, "发生异常"); } //开发环境抛出全部异常 //if (_hostEnvironment.IsDevelopment()) return; context.Result = new ObjectResult(ApiResult.Error(context.Exception.Message)); context.ExceptionHandled = true; }
public static async Task <ApiResult <List <ZzkDocumentViewModel> > > List(Token token, int pageIndex, string category, string keyword) { //var result=null; try { string url = string.Format(Constact.Zzk, category, keyword, pageIndex); var result = await HttpBase.GetAsync(url, null, token); if (result.IsSuccess) { List <ZzkDocumentViewModel> list; if (!string.IsNullOrEmpty(result.Message)) { //errorAction("网络请求失败:" + response.StatusCode); list = JsonConvert.DeserializeObject <List <ZzkDocumentViewModel> >(result.Message); return(ApiResult.Ok(list)); } // return ApiResult.Ok(null); } return(ApiResult <List <ZzkDocumentViewModel> > .Error(result.Message)); } catch (Exception ex) { return(ApiResult <List <ZzkDocumentViewModel> > .Error(ex.Message)); } }
public async Task <ActionResult> UpdateAsync(Person p) { try { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var repository = new EmployeeContext(); var tryFind = await repository.Person.FirstOrDefaultAsync(x => x.Id == p.Id); if (tryFind != null) { tryFind.Address = p.Address; tryFind.Age = p.Age; tryFind.IdNumber = p.IdNumber; await repository.SaveChangesAsync(); } return(Ok(ApiResult.Ok())); } catch (Exception ex) { return(Ok(ApiResult.Error(ex))); } }
public IActionResult Update([FromForm] StationInfo info) { if (string.IsNullOrWhiteSpace(info.Name)) { return(Json(ApiResult.Error(ErrorCode.LogicalError, "参数错误"))); } var old = ZeroApplication.Config[info.Name]; if (old == null) { return(Json(ApiResult.Error(ErrorCode.LogicalError, "参数错误"))); } var config = new StationConfig { Name = info.Name, Description = info.Description, StationAlias = string.IsNullOrWhiteSpace(info.Alias) ? new List <string>() : info.Alias.Trim().Split(new char[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries).ToList() }; if (!ZeroApplication.Config.Check(old, config)) { return(Json(ApiResult.Error(ErrorCode.LogicalError, "名称存在重复"))); } return(Json(ZeroManager.Update(config))); }
public static async Task <ApiResult <string> > GetNewsDetail(Token token, int id) { try { string url = string.Format(Constact.NewsDetail, id); var result = await HttpBase.GetAsync(url, null, token); if (result.IsSuccess) { var articleDetail = result.Message; //successAction(list); return(ApiResult.Ok(articleDetail)); } else { return(ApiResult <string> .Error(result.Message)); //errorAction(result.Message); } } catch (Exception ex) { //errorAction(ex.StackTrace.ToString()); return(ApiResult <string> .Error(ex.Message)); } }
public async Task <ApiResult <object> > PutFileAsync( string url, byte[] bytes ) { using (var client = new HttpClient()) { try { using (HttpContent httpContent = new ByteArrayContent(bytes)) { //httpContent.Headers.Add("Content-MD5", Md5Utils.Md5Base64(bytes)); httpContent.Headers.ContentMD5 = Md5Utils.Md5(bytes); httpContent.Headers.ContentLength = bytes.LongLength; httpContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream"); using (var response = await client.PutAsync(url, httpContent)) { if (response.IsSuccessStatusCode) { var str = await response.Content.ReadAsStringAsync(); Console.WriteLine(str); return(new ApiResult()); } return(ApiResult.Error(response.ReasonPhrase)); } } } catch (Exception ex) { return(ApiResult.Error(ex)); } } }
public static async Task <ApiResult <List <NewsCommentViewModel> > > ListNewsComment(Token token, int postId, int pageIndex) { try { string url = string.Format(Constact.NewscommentList, postId, pageIndex, Constact.PageSize); var result = await HttpBase.GetAsync(url, null, token); if (result.IsSuccess) { var list = JsonConvert.DeserializeObject <List <NewsCommentViewModel> >(result.Message); //successAction(list); return(ApiResult.Ok(list)); } else { return(ApiResult <List <NewsCommentViewModel> > .Error(result.Message)); //errorAction(result.Message); } } catch (Exception ex) { //errorAction(ex.StackTrace.ToString()); return(ApiResult <List <NewsCommentViewModel> > .Error(ex.Message)); } }
public ApiResult UpdateUser([FromBody] UserModel userModel) { _userService.Update(userModel); string error = _notifyValidationHandler.GetErrorList().Select(s => s.Value).FirstOrDefault(); if (!string.IsNullOrEmpty(error)) { return(ApiResult.Error(HttpStatusCode.BAD_REQUEST, error)); } IList <Claim> claims = new List <Claim>() { new Claim("account", userModel.Account), new Claim("username", userModel.Username), new Claim("sex", userModel.Sex), new Claim("birthDate", string.IsNullOrEmpty(userModel.BirthDate)?"":userModel.BirthDate), new Claim("email", string.IsNullOrEmpty(userModel.Email)?"":userModel.Email), new Claim("sign", string.IsNullOrEmpty(userModel.Sign)?"":userModel.Sign), new Claim("phone", userModel.Phone), new Claim("headPhoto", JsonHelper.DeserializeObject <UserModel>(new JWT(_httpContext).ResolveToken()).HeadPhoto) }; string jwtToken = new JWT(_cacheClient).CreateToken(claims); if (Response.Headers.ContainsKey("refreshToken")) { Response.Headers.Remove("refreshToken"); } Response.Headers.Add("refreshToken", jwtToken); return(ApiResult.Success()); }
/// <summary> /// 动作运行前 /// </summary> /// <param name="filterContext"></param> public override void OnActionExecuting(HttpActionContext filterContext) { //没有配置访问范围与访问者类型的API是不能访问的 if (_option == ApiAccessOption.None && _option < ApiAccessOption.Anymouse) { throw new HttpResponseException(filterContext.Request.ToResponse(ApiResult.Error(ErrorCode.DenyAccess))); } //公开、内部必须有其一,否则不能访问 if (!_option.HasFlag(ApiAccessOption.Public)) { if (!_option.HasFlag(ApiAccessOption.Internal)) { throw new HttpResponseException(filterContext.Request.ToResponse(ApiResult.Error(ErrorCode.DenyAccess))); } if (ApiContext.RequestContext == null || ApiContext.RequestContext.ServiceKey == GlobalVariable.ServiceKey) { throw new HttpResponseException(filterContext.Request.ToResponse(ApiResult.Error(ErrorCode.DenyAccess))); } } //非匿名用户时用户类型校验(员工、商家类型未校验 if (!_option.HasFlag(ApiAccessOption.Anymouse)) { if (_option.HasFlag(ApiAccessOption.Customer) && (ApiContext.Customer == null || ApiContext.Customer.UserId <= 0)) { throw new HttpResponseException(filterContext.Request.ToResponse(ApiResult.Error(ErrorCode.DenyAccess))); } } base.OnActionExecuting(filterContext); }
public IActionResult Add() { try { var result = IocHelper.Create <PlanManage>().NewPlan(new ClientPlan { plan_type = (plan_date_type)GetIntArg("plan_type"), plan_value = GetShortArg("plan_value"), plan_repet = GetIntArg("plan_repet"), description = GetArg("description"), command = GetArg("command"), station = GetArg("station"), context = GetArg("context"), argument = GetArg("argument"), no_skip = GetBoolArg("no_skip"), plan_time = GetDateArg2("plan_time1"), skip_set = GetIntArg("skip_set") }); return(new JsonResult(result)); } catch (Exception ex) { return(new JsonResult(ApiResult.Error(ErrorCode.LocalException, ex.Message))); } }
/// <summary> /// 发送HttpPost请求 /// </summary> /// <param name="url">请求地址</param> /// <param name="jsonParam">Json格式的post参数</param> /// <returns></returns> public async Task <string> PostAsync(string url, string jsonParam) { try { var uri = new Uri(url); var origin = uri.GetLeftPart(UriPartial.Authority); var restClient = new RestClient(origin); var request = new RestRequest(uri.PathAndQuery, Method.POST); request.AddJsonBody(jsonParam); request.AddHeader("from", _headFrom); var response = await restClient.ExecuteAsync(request); var responseContent = response.Content; if (response.StatusCode != System.Net.HttpStatusCode.OK) { _logger.LogError($"HttpPost方式请求数据返回值错误,状态码:{(int)response.StatusCode},返回值:{responseContent}"); } return(responseContent); } catch (Exception ex) { _logger.LogError(ex, "HttpPost方式请求数据出现错误"); return(JsonHelper.Serialize(ApiResult.Error("服务接口调用失败"))); } }
public static ApiResult Command(params string[] commands) { if (!ZeroApplication.ZerCenterIsRun) { return(ApiResult.Error(ErrorCode.LocalError, "系统未就绪")); } if (commands.Length == 0 || commands.Any(p => p == null)) { return(ApiResult.Error(ErrorCode.LogicalError, "参数错误")); } var value = SystemManager.Instance.CallCommand(commands.ToArray()); if (!value.InteractiveSuccess) { return(ApiResult.Error(ErrorCode.NetworkError)); } switch (value.State) { case ZeroOperatorStateType.NotSupport: return(ApiResult.Error(ErrorCode.LogicalError, "不支持的操作")); case ZeroOperatorStateType.Ok: var _result = ApiValueResult.Succees(value.GetValue(ZeroFrameType.Context) ?? value.State.Text()); _result.Status = new ApiStatusResult { ErrorCode = ErrorCode.Success, ClientMessage = "操作成功" }; return(_result); default: return(ApiResult.Error(ErrorCode.LogicalError, value.State.Text())); } }
public async Task <ApiResult> PostComment() { string content = Request.Form["content"]; int articleId = Convert.ToInt32(Request.Form["articleId"]); string revicer = Request.Form["revicer"]; string replyId = Request.Form["replyId"]; int commentType = Convert.ToInt32(Request.Form["commentType"]); try { CommentDTO commentDTO = new CommentDTO(); commentDTO.Content = content; commentDTO.AdditionalData = replyId; commentDTO.PostUser = Auth.GetLoginUser().Account; commentDTO.Revicer = revicer; commentDTO.CommentType = commentType; await _articleService.PostComment(articleId, commentDTO); return(ApiResult.Success()); } catch (AuthException) { return(ApiResult.Error(HttpStatusCode.FORBIDDEN, "not login")); } }
public override void OnActionExecuting(ActionExecutingContext context) { if (context.ModelState.IsValid) { return; } var errorMessage = "The request data is invalid."; foreach (var key in context.ModelState.Keys) { var value = context.ModelState[key]; if (value.Errors != null && value.Errors.Count > 0) { var message = value.Errors[0].ErrorMessage; errorMessage = string.IsNullOrEmpty(message) ? $"The value of {key} field is invalid." : message; break; } } context.Result = new JsonResult(ApiResult.Error(errorMessage, 400)) { StatusCode = StatusCodes.Status200OK }; }
public ApiResult <CommandVM> GetOne() { //ako ima pravo pristupa if (false) { return(ApiResult <CommandVM> .Error(1, "Nema pravo pristupa")); } Command k = _db.Command .Where(x => !x.DateExecuteStart.HasValue) .OrderBy(x => x.Id) .FirstOrDefault(); if (k == null) { return(ApiResult <CommandVM> .OK(null)); } k.DateExecuteStart = DateTime.Now; _db.SaveChanges(); CommandVM model = new CommandVM { Id = k.Id, CommandType = k.CommandType }; return(ApiResult <CommandVM> .OK(model)); }
public ApiResult Login() { string account = Request.Form["account"]; string password = Request.Form["password"]; try { UserDTO user = _userService.Login(account, password); IList <Claim> claims = new List <Claim>() { new Claim("account", user.Account), new Claim("username", user.Username), new Claim("sex", user.Sex), new Claim("birthDate", user.BirthDate), new Claim("email", string.IsNullOrEmpty(user.Email)?"":user.Email), new Claim("sign", string.IsNullOrEmpty(user.Sign)?"":user.Sign), new Claim("phone", string.IsNullOrEmpty(user.Phone)?"":user.Phone), new Claim("headPhoto", user.HeadPhoto) }; string token = Auth.CreateToken(claims); return(ApiResult.Success(token)); } catch (AuthException ex) { return(ApiResult.Error("403", ex.Message)); } }
public ApiResult SwitchAbTest(int testId, bool value) { try { //получим id контента (это должен быть AbTest) var contentId = _dbConnector.GetContentIdForItem(testId); if (contentId == 0) { return(ApiResult.Error(Response, $"Not found content with article {testId}")); } //получим название поля Enabled в найденном контенте, чтобы использовать для метода MassUpdate //на разных базах эти названия в теории могут отличаться, инвариант - это NetName var enabledField = _metaInfoRepository.GetContentAttributeByNetName(contentId, "Enabled"); if (enabledField == null) { return(ApiResult.Error(Response, $"Field with netname 'Enabled' not found in content {contentId}")); } var testUpdate = new Dictionary <string, string> { [SystemColumnNames.Id] = testId.ToString(), [enabledField.ColumnName] = (value ? 1 : 0).ToString() }; _dbConnector.MassUpdate(contentId, new[] { testUpdate }, GetUserId()); return(ApiResult.Success()); } catch (Exception ex) { return(ApiResult.Error(Response, ex.Message)); } }