簡體   English   中英

確認 Email 在 asp.net 內核 web api

[英]Confirm Email in asp.net core web api

此 API 適用於移動應用程序。 目的是讓用戶在注冊時確認 email。 當用戶注冊時,會生成一個確認鏈接並通過 email 發送。 我在 MVC 項目中以同樣的方式完成了它,它運行良好,但在 Web API 項目中看起來它不會削減。 現在,當用戶單擊該鏈接時,應該點擊相應的操作方法並完成工作。

唯一的問題是, ConfirmEmail操作方法在單擊確認鏈接時沒有被觸發,盡管它看起來不錯。

以下是可能有幫助的主要配置

MVC 服務配置

services.AddMvc(options => 
                    {  
                        options.EnableEndpointRouting = true;
                        options.Filters.Add<ValidationFilter>();
                    })
                    .AddFluentValidation(mvcConfiguration => mvcConfiguration.RegisterValidatorsFromAssemblyContaining<Startup>())
                    .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_3_0);

身份服務

 public async Task<AuthenticationResult> RegisterAsync(string email, string password)
        {
            var existingUser = await _userManager.FindByEmailAsync(email);

            if(existingUser != null)
            {
                return new AuthenticationResult { Errors = new[] { "User with this email address exists" } };
            }

            // generate user
            var newUser = new AppUser
            {
                Email = email,
                UserName = email
            };

            // register user in system
            var result = await _userManager.CreateAsync(newUser, password);

            if (!result.Succeeded)
            {
                return new AuthenticationResult
                {
                    Errors = result.Errors.Select(x => x.Description)
                };
            }

            // when registering user, assign him user role, also need to be added in the JWT!!!
            await _userManager.AddToRoleAsync(newUser, "User");

            // force user to confirm email, generate token
            var token = await _userManager.GenerateEmailConfirmationTokenAsync(newUser);

            // generate url
            var confirmationLink = _urlHelper.Action("ConfirmEmail", "IdentityController",
                    new { userId = newUser.Id, token = token }, _httpRequest.HttpContext.Request.Scheme);

            // send it per email
            var mailresult = 
                await _emailService.SendEmail(newUser.Email, "BingoApp Email Confirmation",
                $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(confirmationLink)}'>clicking here</a>.");
            if (mailresult)
                return new AuthenticationResult { Success = true };
            else
                return new AuthenticationResult { Success = false, Errors = new List<string> { "Invalid Email Address"} };
        }

Controller

        [HttpPost(ApiRoutes.Identity.Register)]
        public async Task<IActionResult> Register([FromBody] UserRegistrationRequest request)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(new AuthFailedResponse
                {
                    Errors = ModelState.Values.SelectMany(x => x.Errors.Select(xx => xx.ErrorMessage))
                });
            }

            // register the incoming user data with identity service
            var authResponse = await _identityService.RegisterAsync(request.Email, request.Password);          

            if (!authResponse.Success)
            {
                return BadRequest(new AuthFailedResponse
                {
                    Errors = authResponse.Errors
                });
            }

            // confirm registration
            return Ok();
        }


        [HttpGet]
        public async Task<IActionResult> ConfirmEmail(string userId, string token)
        {
            if (userId == null || token == null)
            {
                return null;
            }

            var user = await _userManager.FindByIdAsync(userId);

            if (user == null)
            {
                return null;
            }

            var result = await _userManager.ConfirmEmailAsync(user, token);

            if (result.Succeeded)
            {
               await _emailService.SendEmail(user.Email, "BingoApp - Successfully Registered", "Congratulations,\n You have successfully activated your account!\n " +
                    "Welcome to the dark side.");
            }

            return null;
        }

您的_urlHelper.Action(..)在我看來有點可疑。

我不確定您是否應該傳遞完整的 controller name ,即包括實際單詞controller

嘗試_urlHelper.Action("ConfirmEmail", "Identity",而不是。

提示:我嘗試通過使用nameof(IdentityController)來避免使用此類魔術字符串,因為它將返回 controller 名稱而沒有 controller 后綴。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM