public async Task <IActionResult> Create(ApiResource model) { if (!ModelState.IsValid) { return(View(model)); } if (_context.ApiResources.Any(x => x.Name == model.Name)) { ModelState.AddModelError(string.Empty, "Name can't be used because is used by another api resource"); } model.Id = await _context.ApiResources.MaxAsync(x => x.Id) + 1; try { await _context.ApiResources.AddAsync(model); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (Exception e) { Debug.WriteLine(e); ModelState.AddModelError(string.Empty, "Fail to add new api resource, try contact administrator!"); return(View(model)); } }
public async Task <IActionResult> Create(ApiClientCreateViewModel model) { if (!ModelState.IsValid) { model.AvailableApiScopes = GetAvailableApiScopes(); return(View()); } try { var cl = new Client { ClientName = model.ClientName, ClientId = model.ClientId, AllowedGrantTypes = GetGrantTypesFromViewModel(model), ClientUri = model.ClientUri, AllowOfflineAccess = true, ClientSecrets = new List <Secret> { new Secret("very_secret".Sha256()) } }; var parsed = cl.ToEntity(); parsed.Id = await _configurationDbContext.Clients.MaxAsync(x => x.Id) + 1; foreach (var item in parsed.AllowedGrantTypes) { item.Id = new Random().Next(1, 9999); } _configurationDbContext.Clients.Add(parsed); await _configurationDbContext.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } catch (DbUpdateException ex) { if (ex.InnerException is SqlException exception) { switch (exception.Number) { case 2601: ModelState.AddModelError(string.Empty, "The API Client Already Exists"); //_logger.LogError(exception, "The API Client already exists"); break; default: ModelState.AddModelError(string.Empty, "An unknown error occured"); //_logger.LogError(exception, "Unknown sql error"); break; } } else { //_logger.LogError(ex, "A db error occured"); ModelState.AddModelError(string.Empty, ex.Message); } } catch (Exception e) { ModelState.AddModelError(string.Empty, e.Message); } model.AvailableApiScopes = GetAvailableApiScopes(); return(View(model)); }