コード例 #1
0
        public async Task <IActionResult> Create(CreateCertificateViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            if (await _store.FindByName(model.Name) != null)
            {
                ModelState.AddModelError("Name", "Name already in use");
                return(View(model));
            }

            if (model.File.Length > MaximumCertificateSizeInBytes)
            {
                ModelState.AddModelError("File", $"Certificate file too large (limited to {MaximumCertificateSizeInBytes / 1024} kB");
                return(View(model));
            }

            X509Certificate2 certificate;

            try
            {
                using (var stream = model.File.OpenReadStream())
                    certificate = Certificate.FromStream(stream, model.Password);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("File", $"Invalid certificate file: {ex.Message}");
                return(View(model));
            }

            await _store.Create(new Domain.Entities.Certificate
            {
                Name             = model.Name,
                Data             = certificate.RawData,
                OriginalFileName = model.File.FileName,
                Subject          = certificate.Subject,
                ValidFrom        = certificate.NotBefore,
                ValidTo          = certificate.NotAfter
            });

            return(RedirectToAction(nameof(List)));
        }