public ActionResult Create() { var accessToken = GetAdminAccessToken(INAUTHURL, INAPIKEY, INADMINUSERNAME, INADMINPASSWORD); var securityQuestions = GetSecurityQuestions(INUSERSSECURITYQUESTIONSURL, INAPIKEY, accessToken); var model = new CreateModel() { SecurityQuestions = securityQuestions }; return View(model); }
public bool CourseExists(CreateModel createModel) { var courseCodeExists = Find.Element(By.CssSelector("tr:last-of-type td.course-code")).Text.Equals(createModel.CourseCode); var courseTitleExists = Find.Element(By.CssSelector("tr:last-of-type td.course-title")).Text.Equals(createModel.CourseTitle); var courseDescriptionExists = Find.Element(By.CssSelector("tr:last-of-type td.course-description")).Text.Equals(createModel.CourseDescription); return(courseCodeExists && courseTitleExists && courseDescriptionExists); }
public void OnGet() { // Arrange var context = new Mock <IConfigurationDbContext>(); var create = new CreateModel(context.Object); // Act var get = create.OnGet(); // Assert Assert.NotNull(create.IdentityResource); Assert.IsType <PageResult>(get); }
public async Task <JsonResult> Create(CreateModel <AccountAdmin> query, CancellationToken cancelllationToken) { SetAddNew(query); await _service.AddAsync(query.Entity, cancelllationToken); var count = await _service.SaveAsync(cancelllationToken); return(new JsonResult(new { Success = count > 0, Entity = query.Entity })); }
//[ValidateAntiForgeryToken] public ActionResult Create(CreateModel offerCreateModel) { var offer = _mapper.Map <Offer>(offerCreateModel); offer.CreatedAt = DateTime.Now; //nie bedzie nulla bo przeszedl autoryzacje var userId = int.Parse(HttpContext.User.Claims.FirstOrDefault(c => c.Type.Equals("Id")).Value); _offerRepository.InsertOffer(offer, userId); return(View()); }
public void OnGet() { // Arrange var create = new CreateModel(_roleManager.Object, _userManager.Object); // Act var get = create.OnGet(); // Assert Assert.NotNull(create.Role); Assert.Empty(create.Users); Assert.IsType <PageResult>(get); }
public async Task <IActionResult> Create(CreateModel model) { if (ModelState.IsValid) { if (model.Password != model.ConfirmPassword) { ModelState.AddModelError("ConfirmPassword", "Passwords do not match"); return(View(model)); } ApplicationUser user = new ApplicationUser { UserName = model.Username, Email = model.Email }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (!await _roleManager.RoleExistsAsync("Administrators")) { result = await _roleManager.CreateAsync(new IdentityRole("Administrators")); if (!result.Succeeded) { ModelState.AddModelError("", "Error occured when creating the account"); return(View(model)); } } result = await _userManager.AddToRoleAsync(user, "Administrators"); if (!result.Succeeded) { ModelState.AddModelError("", "Error occured when creating the account"); return(View(model)); } return(RedirectToAction("Index")); } else { foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } } return(View(model)); }
public async Task OnPostAsync() { // Arrange var user = new User { Id = Guid.NewGuid() }; var role = new Role { Id = Guid.NewGuid(), Name = "Name", UserRoles = new List <UserRole> { new UserRole { User = user, UserId = user.Id } } }; _userManager.Setup(x => x.FindByIdAsync($"{user.Id}")).ReturnsAsync(user); var create = new CreateModel(_roleManager.Object, _userManager.Object) { Role = role }; // Act var post = await create.OnPostAsync().ConfigureAwait(false); // Assert foreach (var userRole in role.UserRoles) { _userManager.Verify(x => x.FindByIdAsync($"{userRole.UserId}"), Times.Once); _userManager.Verify( x => x.AddClaimAsync(userRole.User, It.Is <Claim>( y => y.Type == ClaimTypes.Role && y.Value == role.Name)), Times.Once); } _roleManager.Verify( x => x.CreateAsync(It.Is <Role>(y => y.Name.Equals(role.Name))), Times.Once); var result = Assert.IsType <RedirectToPageResult>(post); Assert.Equal("./Details/Index", result.PageName); Assert.Collection(result.RouteValues, routeValue => { var(key, value) = routeValue; Assert.Equal(nameof(Role.Id), key); Assert.Equal(role.Id, value); }); }
public async Task <JsonResult> Create(CreateModel model) //public async Task<JsonResult> Create(CreateModel model) { JsonResponse <AppUser> response = new JsonResponse <AppUser>(); if (ModelState.IsValid) { AppUser user = new AppUser { FirstName = model.FirstName.ToLower(), LastName = model.LastName.ToLower(), UserName = model.Email.ToLower(), Email = model.Email.ToLower(), IsEnabled = true, EmailConfirmed = true, LockoutEnabled = false }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { AppUser newUser = await userManager.FindByEmailAsync(user.Email); response.Data.Add(newUser); // Now lets add them as an invited user await this.userManager.AddToRoleAsync(newUser, "InvitedGuest"); return(Json(response)); } else { foreach (IdentityError error in result.Errors) { response.Error.Add(new Error() { Name = "admin", Description = error.Description.ToString() }); } } } else { response.Error.Add(new Error() { Description = "Failed Validation", Name = "AdminCreate" }); } return(Json(response)); }
public async Task <IActionResult> Create([FromBody] CreateModel model) { var routeBase = await _routeBaseService.CreateAsync(new RouteBase { Origin = new Point { Description = model.PointOrigin }, Destination = new Point { Description = model.PointDestination } }); return(Ok(routeBase)); }
public async Task ShouldCreateNewNonExistingArticleAndRedirect_GivenUserIsAuthenticated() { var expectedCommand = new CreateNewArticleCommand { Topic = _topic, AuthorId = userId, Content = _content, AuthorName = username }; _mediator.Setup(mediator => mediator.Send(It.IsAny <CreateNewArticleCommand>(), It.IsAny <CancellationToken>())) .Returns(() => Task.FromResult(new CommandResult { Successful = true, ObjectId = _expectedSlug })); _mediator.Setup(mediator => mediator.Send(It.IsAny <GetIsTopicAvailableQuery>(), It.IsAny <CancellationToken>())) .Returns(() => Task.FromResult(false)); _mediator.Setup(mediator => mediator.Send(It.IsAny <GetArticlesToCreateFromArticleQuery>(), It.IsAny <CancellationToken>())) .Returns(Task.FromResult((_expectedSlug, new string[] { }))); _sut = new CreateModel(_mediator.Object, _mapper, new NullLoggerFactory()) { Article = new ArticleCreate { Topic = _topic, Content = _content } }; //we depend on a valid ClaimsPrinciple!! No check on User yet before sending the command _sut.AddPageContext(username, userId); var result = await _sut.OnPostAsync(); Assert.IsType <RedirectToPageResult>(result); Assert.Equal(_expectedSlug, ((RedirectToPageResult)result).RouteValues["slug"]); _mediator.Verify(m => m.Send( It.Is <GetIsTopicAvailableQuery>(request => request.ArticleId.Equals(0) && request.Topic.Equals(_topic)), It.Is <CancellationToken>(token => token.Equals(CancellationToken.None))), Times.Once ); _mediator.Verify(m => m.Send( It.Is <CreateNewArticleCommand>(request => request.Topic.Equals(expectedCommand.Topic) && request.AuthorName.Equals(expectedCommand.AuthorName) && request.Content.Equals(expectedCommand.Content) && request.AuthorId.Equals(userId)), It.Is <CancellationToken>(token => token.Equals(CancellationToken.None))), Times.Once); }
public async Task AddInfoAsync__Add_succeeded__Should_return_201OK_response_with_added_element() { _mapperMock.Setup(x => x.Map <VisitInfo>(It.IsNotNull <VisitInfoDto>())).Returns(_info); _mapperMock.Setup(x => x.Map <VisitInfoDto>(It.IsNotNull <VisitInfo>())).Returns(_infoDto); _infoDbServiceMock.Setup(x => x.AddAsync(It.IsAny <VisitInfo>())).ReturnsAsync(_info); _infoDbServiceMock.Setup(x => x.RestrictedAddAsync(It.IsAny <VisitInfo>())).ReturnsAsync(_info); var controller = new VisitInfoController(_infoDbServiceMock.Object, _logger, _mapperMock.Object); var infoDto = CreateInfoDto(CreateModel.CreateInfo()); var result = await controller.AddInfoAsync(infoDto); (result as ObjectResult).StatusCode.Should().Be(201); ((result as ObjectResult).Value as ResponseWrapper).Error.Should().BeEquivalentTo(new ApiError()); }
//生成整个轨道模型 public void CreateTrailer(GlobalVaribles.Trailer_Para trailer_Para) { GameObject trailer = CreateEmpty(trailer_Para.trailerName); GameObject in_trailer = new GameObject("in_trailer"); GameObject out_trailer = new GameObject("out_trailer"); in_trailer.transform.parent = trailer.transform; out_trailer.transform.parent = trailer.transform; //创建内轨道 //曲线 GameObject CurveGroup_in = new GameObject("CurveGroup_in"); CurveGroup_in.transform.parent = in_trailer.transform; for (int i = 0; i < GlobalVaribles.in_curve_Para_list.Count; i++) { GameObject curve = CreateModel.CreateCurve(GlobalVaribles.in_curve_Para_list[i]); curve.transform.parent = CurveGroup_in.transform; } //直线组 GameObject LineGroup_in = new GameObject("LineGroup_in"); LineGroup_in.transform.parent = in_trailer.transform; for (int i = 0; i < GlobalVaribles.in_line_Para_list.Count; i++) { GameObject cube = CreateModel.CreateLine(GlobalVaribles.in_line_Para_list[i]); cube.transform.parent = LineGroup_in.transform; } //创建外轨道 //曲线组 GameObject CurveGroup_out = new GameObject("CurveGroup_out"); CurveGroup_out.transform.parent = out_trailer.transform; for (int i = 0; i < GlobalVaribles.out_curve_Para_list.Count; i++) { GameObject curve = CreateModel.CreateCurve(GlobalVaribles.out_curve_Para_list[i]); curve.transform.parent = CurveGroup_out.transform; } //直线 GameObject LineGroup_out = new GameObject("LineGroup_out"); LineGroup_out.transform.parent = out_trailer.transform; for (int i = 0; i < GlobalVaribles.out_line_Para_list.Count; i++) { GameObject cube = CreateModel.CreateLine(GlobalVaribles.out_line_Para_list[i]); cube.transform.parent = LineGroup_out.transform; } //ModelTool.CreatePrefabObj(trailer, "Trailer"); }
public async Task <IActionResult> Create(CreateModel model) { //model.success = true; //model.message = "AAAAAAAAAAAAAAAAAA"; if (ModelState.IsValid) { int codeId_ = 0; int.TryParse(model.CodeId?.Trim(), out codeId_); string msg = CheckProvidedCode(codeId_, model.Code ?? ""); if (msg == "") { AppUser user = new AppUser { UserName = model.Name, Email = model.Email }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { if (!UpdateUser_CodeStatus(user, codeId_, model.Code)) { model.message = "There was problem to update Code table!"; } return(RedirectToAction("Index")); } else { foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } } else { model.message = msg; } } if (model.success) { return(Json(new { success = model.success, message = model.message })); } else { return(PartialView("Create", model)); } }
public async Task <IActionResult> SignUp(CreateModel model) { if (ModelState.IsValid) { if (model.RepeatPassword != model.Password) { ModelState.AddModelError("IncorrectPassword", "Please, enter your password again."); return(View()); } AppUser user = new AppUser { UserName = model.UserName, FirstName = model.FirstName, LastName = model.LastName, Email = model.Email, CompanyName = model.CompanyName, PhoneNumber = (model.PhoneNumber != "") ? model.PhoneNumber : "", RegistrationDate = DateTime.Now, UpdatedAt = DateTime.Now, Remark = model.Remark, Status = "Inactive", CreatedAt = DateTime.Now }; IdentityResult result = await userManager.CreateAsync(user, model.Password); if (result.Succeeded) { foreach (AppUser admin in userManager.Users .Where(u => u.CompanyName == model.CompanyName)) { if (await userManager.IsInRoleAsync(admin, "Admin")) { SendMail(admin.Id, user.Id); } } /*TODO: add user to userDetails*/ return(RedirectToAction("SuccessSignUp")); } else { foreach (IdentityError error in result.Errors) { ModelState.AddModelError("", error.Description); } } } return(View()); }
public virtual ActionResult Create(CreateModel createModel) { if (!ModelState.IsValid) { createModel.ParentCourseList = GetParentCourseList(); return(View(createModel)); } var course = _createModelToCourseMapper.Build(createModel); _genericRepository.Add(course); _genericRepository.Save(); return(RedirectToAction(Actions.Index())); }
public IActionResult Create(CreateModel model) { string userName = User.Identity.Name; string userId = _userService.GetUserByNameAsync(userName).Result.Id; if (ModelState.IsValid) { _blogService.Create(model, userId, out Guid blogId); return(RedirectToRoute("Details", new { urlUserName = userName, blogId = blogId })); } else { return(View(model)); } }
public void ShouldMapCreateModelToClassPeriod() { SetUp(); var classPeriodEntity = new Web.Data.Entities.ClassPeriod(); var classPeriodCreateModel = new CreateModel { ClassPeriodName = "Period 1" }; var createModeltoClassPeriodMapper = new CreateModelToClassPeriodMapper(_schoolRepository); createModeltoClassPeriodMapper.Map(classPeriodCreateModel, classPeriodEntity); classPeriodEntity.ClassPeriodName.ShouldBe("Period 1"); classPeriodEntity.SchoolId.ShouldBe(1); }
public async Task <IActionResult> Create([FromBody] CreateModel model) { var stepToAdd = _mapper.Map <Step>(model); stepToAdd.Start = new Point { Description = model.PointStart }; stepToAdd.End = new Point { Description = model.PointEnd }; var step = await _stepService.CreateAsync(stepToAdd); return(Ok(step)); }
// (Create Page) selects a single record from the Makes table. // GET: /Model/Create?makeId public async Task <IActionResult> Create(int?makeId) { ViewData["Title"] = "Models | Create | "; VehicleMakeVM makeForModel = mapper.Map <VehicleMakeVM>(await modelService.GetMakeAsync(makeId)); var createModel = new CreateModel { Abrv = makeForModel.Abrv, MakeId = makeForModel.Id, DetailMakeName = makeForModel.Name }; return(View(createModel)); }
public async Task <ActionResult <RestaurantModel> > Create([FromBody] CreateModel createModel) { Restaurant restaurant = _mapper.Map <Restaurant>(createModel); try { restaurant = await _restaurantService.Create(restaurant, UserAuth().Id); return(CreatedAtAction("GetById", new { id = restaurant.Id }, FormatForUser(restaurant))); } catch (ApplicationException ex) { return(BadRequest(new { message = ex.Message })); } }
private void SetUp() { _createModel = new CreateAssessmentModelBuilder().Build(); _assessment = new AssessmentBuilder().Build(); _genericRepositoryStub = Substitute.For <IGenericRepository>(); var fourthGradeLevelDescriptor = new GradeLevelDescriptor { GradeLevelDescriptorId = 99, GradeLevelTypeId = 100 }; _genericRepositoryStub.Get(Arg.Any <GradeLevelTypeDescriptorQuery>()) .Returns(fourthGradeLevelDescriptor); }
//生成所有小车 public void CreateCars() { //创建车组 GameObject carGroup = new GameObject(); carGroup.name = "CarGroup"; for (int i = 0; i < GlobalVaribles.car_list.Count; i++) { GameObject carObj = CreateModel.CreateCar(GlobalVaribles.car_list[i]); //更新allCars和allocableCars数组 GlobalVaribles.allCars.Add(GlobalVaribles.car_list[i]); GlobalVaribles.allocableCars.Add(GlobalVaribles.car_list[i]); carObj.transform.parent = carGroup.transform; } }
public async Task <IActionResult> Create([FromBody] CreateModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var flight = model.ToDomain(); await _repository.CreateAsync(flight); var url = Url.RouteUrl("GetFlightById", new { id = flight.Id }); var summary = await _view.GetByIdAsync(flight.Id); return(Created(url, summary).WithHeader("ETag", summary.ETag)); }
public virtual ActionResult Create(CreateModel createModel) { if (!ModelState.IsValid) { return(View(createModel)); } var session = new Session(); _createModelToEntityMapper.Map(createModel, session); _genericRepository.Add(session); _genericRepository.Save(); return(RedirectToAction(Actions.Index())); }
public async Task <IActionResult> Create(CreateModel model) { await ValidateReCaptcha(); Validate(model); if (!ModelState.IsValid) { this.CreateAlert(AlertTypeEnum.Warning, ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage).ToList()); return(View(nameof(Create), model)); } GenerateAndSendEmail(model); return(RedirectToAction(nameof(ThankYouController.Index), "ThankYou")); }
public async Task OnPostCreateCalificaciones_VerSiRealmenteCrea() { // Arrange //Preparamos un contexto que guarde la base de datos en memoria ram. var OptionsBuilder = new DbContextOptionsBuilder <IdentityContext>() .UseInMemoryDatabase("InMemoryDb"); IdentityContext TestIdentityContext = new IdentityContext(OptionsBuilder.Options); //Creamos una calificacion esperada Calificacion CalificacionEsperada = new Calificacion() { ID = 1, Nota = 5, Descripcion = "Descripcion de prueba" }; // Act //Creamos una pagina de tipo CreateModel (de Calificaciones), la cual es la que se encarga de la logica //de crear calificaciones en bd. CreateModel PageCreateModel = new CreateModel(TestIdentityContext); //Introducimos una calificacion en el modelo de la pagina que creamos, a mano Seteamos los valores de //la calificacion de esa página PageCreateModel.Calificacion = new Calificacion() { ID = 1, Nota = 5, Descripcion = "Descripcion de prueba" }; //Simulamos un post que envíe el formulario de la pagina y por ende guarde en bd la calificacion que ingresamos en esa pagina await PageCreateModel.OnPostAsync(); // Assert //Buscamos usando el contexto la Calificacion recien creada por id Calificacion CalificacionRecibida = await TestIdentityContext.Calificacion.FindAsync(1); //Comparamos que la que creamos en el modelo de la pagina y por ende mandamos a crear en bd, //y la calificacion que recibimos de bd con id 1, tengan igual descripcion y nota Assert.Equal( CalificacionEsperada.Descripcion.ToString(), CalificacionRecibida.Descripcion.ToString()); Assert.Equal( CalificacionEsperada.Nota.ToString(), CalificacionRecibida.Nota.ToString()); //Si esto no falla, concluimos que la pagina de calificaciones (de tener bien seteado el modelo), //guarda sin problemas una calificacion en bd cuando no hay nada ingresado }
public async Task OnPostCreateEspecialidades_VerSiRealmenteCrea() { // Arrange //Preparamos un contexto que guarde la base de datos en memoria ram. var OptionsBuilder = new DbContextOptionsBuilder <IdentityContext>() .UseInMemoryDatabase("InMemoryDb"); IdentityContext TestIdentityContext = new IdentityContext(OptionsBuilder.Options); //Creamos una Especialidad esperada Especialidad EspecialidadEsperada = new Especialidad() { ID = 1, Area = "Foto Fija", Nivel = "Basico" }; // Act //Creamos una pagina de tipo CreateModel (de Especialidades), la cual es la que se encarga de la logica //de crear Especialidades en bd. CreateModel PageCreateModel = new CreateModel(TestIdentityContext); //Introducimos una Especialidad en el modelo de la pagina que creamos, a mano Seteamos los valores de //la Especialidad de esa página PageCreateModel.Especialidad = new Especialidad() { ID = 1, Area = "Foto Fija", Nivel = "Basico" }; //Simulamos un post que envíe el formulario de la pagina y por ende guarde en bd la Especialidad que ingresamos en esa pagina await PageCreateModel.OnPostAsync(); // Assert //Buscamos usando el contexto la Especialidad recien creada por id Especialidad EspecialidadRecibida = await TestIdentityContext.Especialidad.FindAsync(1); //Comparamos que la que creamos en el modelo de la pagina y por ende mandamos a crear en bd, //y la Especialidad que recibimos de bd con id 1, tengan igual Nivel y Area Assert.Equal( EspecialidadEsperada.Nivel.ToString(), EspecialidadRecibida.Nivel.ToString()); Assert.Equal( EspecialidadEsperada.Area.ToString(), EspecialidadRecibida.Area.ToString()); //Si esto no falla, concluimos que la pagina de Especialidades (de tener bien seteado el modelo), //guarda sin problemas una Especialidad en bd cuando no hay nada ingresado }
public async Task <IHttpActionResult> Create(CreateModel model) { using (var uofw = CreateUnitOfWork) { var ret = _categoryService.Create(uofw, new Category() { Color = model.Color, Description = model.Description, Title = model.Title, ImageID = model.ImageID }); return(Ok(ret)); } }
public bool Create(CreateModel model, string userId, out Guid newBlogId) { bool createResult; Blog dbBlog = new Blog { CoverImageUrl = model.CoverImageUrl, Title = model.Title, Content = model.Content, CreateTime = DateTime.UtcNow, UpdateTime = DateTime.UtcNow, UserId = userId }; createResult = _blogDA.Create(dbBlog); newBlogId = dbBlog.Id; return(createResult); }
private void Validate(CreateModel model) { if (!model.JobHours.Any(j => j.Checked)) { ModelState.AddModelError(nameof(model.JobHours), "At least one value should be selected."); } else if (model.JobHours.Any(m => m.Checked && string.IsNullOrWhiteSpace(m.Hours))) { ModelState.AddModelError(nameof(model.JobHours), $"{DisplayNameHelper.GetDisplayName(model.GetType(), nameof(model.JobHours))} is required."); } if (model.JobType == JobTypeEnum.Doctor.Description() && string.IsNullOrWhiteSpace(model.Specialty)) { ModelState.AddModelError(nameof(CreateModel.Specialty), "Specialty is required for doctor."); } }
public ActionResult Create(CreateModel m) { if (ModelState.IsValid) { using (var db = new Piranha.DataContext()) { // PIRANHA USER // Login sysuser into the current context. db.LoginSys(); var user = new Piranha.Entities.User() { Login = m.Login, Email = m.Email, GroupId = GetUserGroupId() }; if (!String.IsNullOrEmpty(m.Password)) { user.Password = Piranha.Models.SysUserPassword.Encrypt(m.Password); } db.Users.Add(user); // OUR USER dynamic registration = new UserRegistration(m); registration.Register(); if (db.SaveChanges() > 0) { // Make sure that you have implemented the Hook Hooks.Mail.SendPassword if (String.IsNullOrEmpty(m.Password)) { user.GenerateAndSendPassword(db); } } else { return View("RegistrationFailed"); } } return View("Login"); } return View("RegistrationFailed"); }
public ActionResult Create(CreateModel model) { if (ModelState.IsValid) { var accessToken = GetAdminAccessToken(INAUTHURL, INAPIKEY, INADMINUSERNAME, INADMINPASSWORD); string errorMessage; if (TryCreateAccount(INUSERSCREATEURL, INAPIKEY, accessToken, model, out errorMessage)) { //todo: Email user's credentials return View("CreateSuccess"); } else { ModelState.AddModelError(string.Empty, errorMessage); return Create(); } } else { return Create(); } }
private static bool TryCreateAccount(string createUserUrl, string apiKey, string accessToken, CreateModel model, out string errorMessage) { var success = false; errorMessage = string.Empty; try { var requestBody = new { Authority = new { IsTenantAdmin = false, }, Credentials = new { Password = model.Password, Pin = model.Pin, SecurityQuestionAnswers = new[] { new { Answer = model.QuestionOneAnswer, SecurityQuestionId = model.QuestionOneId, }, new { Answer = model.QuestionTwoAnswer, SecurityQuestionId = model.QuestionTwoId, }, new { Answer = model.QuestionThreeAnswer, SecurityQuestionId = model.QuestionThreeId, }, }, Username = model.Username, }, Profile = new { EmailAddress = model.EmailAddress, FirstName = model.FirstName, LastName = model.LastName, } }; using (var httpClient = new HttpClient()) { httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("api-key", apiKey); httpClient.DefaultRequestHeaders.Add("x-sts-accesstoken", accessToken); var httpContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json"); var result = httpClient.PostAsync(createUserUrl, httpContent).Result; if (result.IsSuccessStatusCode) { success = true; } else { errorMessage = result.ReasonPhrase; var content = result.Content.ReadAsStringAsync().Result; dynamic responseJson = JsonConvert.DeserializeObject(content); errorMessage = responseJson.Message.Value; } } } catch (Exception ex) { var baseException = ex.GetBaseException(); errorMessage = "Sorry. An unexpeted error occured, while creating your account."; } return success; }