ASP.NET Web API 2-用户注册电子邮件确认失败

发布时间: 2016/11/7 5:39:36
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

这是一个 Asp.Net WEB Api 项目。我想让用户向网站登记册和向用户授予访问权限之前,请确认他们的电子邮件发送一封电子邮件。我能够注册和生成的电子邮件确认令牌但回调 url 生成失败。这里是我的代码为止。

AccountController.cs

[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
    if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

    IdentityResult result = await authRepository.RegisterUser(userModel);
        IHttpActionResult errorResult = GetErrorResult(result);

    if (errorResult != null)
        {
            return errorResult;
    }


            return Ok();
}

AuthRepository.cs

public async Task<IdentityResult> RegisterUser(UserModel userModel)
{
    IdentityUser user = new IdentityUser
        {
            UserName = userModel.UserName,
                Email = userModel.UserName
    };

    IdentityResult result = await userManager.CreateAsync(user, userModel.Password); //var result

        if (result.Succeeded)
        {
            try
                {
                    var provider = new DpapiDataProtectionProvider("TestWebAPI");
                    userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(provider.Create("EmailConfirmation"));
                    var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);
                    UrlHelper urlHelper = new UrlHelper();
                    var callbackUrl = urlHelper.Action
                        (
                            "ConfirmEmail", "Account",
                            new { userId = user.Id, code = code },
                            protocol: "http"
                        );

                    await userManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm...." + "<a href=\"" + callbackUrl + "\">click here</a>");
        }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
    }
        return result;
}

它失败在哪里我生成的 callbackurl 点。我会得到这个异常:"值不能为 null.\r\nParameter 名称︰ routeCollection"

堆栈跟踪

at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.GenerateUrl(String routeName, String actionName, String controllerName, String protocol, String hostName, String fragment, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, Boolean includeImplicitMvcValues)
   at System.Web.Mvc.UrlHelper.Action(String actionName, String controllerName, Object routeValues, String protocol)
   at TestWebAPI.AuthRepository.<RegisterUser>d__1.MoveNext() in d:\Workspace\VKalpa 2.0\Projects\Test\WebAPI-0.2\TestWebAPI\TestWebAPI\AuthRepository.cs:line 44

有人可以帮我吗?

解决方法 1:

最后,有它的工作。我读了文档和有它的工作...... 下面是我为那些面临问题发送电子邮件在 Asp.Net Web API 的上下文中的代码。所以处理类似的问题,在 MVC 5 web 应用程序的上下文中的例子也是有帮助的。

...
if (result.Succeeded)
            {
                try
                {
                    var provider = new DpapiDataProtectionProvider("TestWebAPI");
                    userManager.UserTokenProvider = new DataProtectorTokenProvider<IdentityUser>(provider.Create("EmailConfirmation"));
                    var code = await userManager.GenerateEmailConfirmationTokenAsync(user.Id);

                    var newRouteValues = new RouteValueDictionary(new { userId = user.Id, code = code});
                    newRouteValues.Add("httproute", true);
                    UrlHelper urlHelper = new System.Web.Mvc.UrlHelper(HttpContext.Current.Request.RequestContext, RouteTable.Routes);
                    string callbackUrl = urlHelper.Action(
                        "ConfirmEmail",
                        "Account",
                        newRouteValues,
                        HttpContext.Current.Request.Url.Scheme
                        );

                    string emailTitle = "Please confirm your account";
                    string emailBody = "<a href='>" + callbackUrl + "'Please click Here to confirm your email</a>";

                    await userManager.SendEmailAsync(user.Id, emailTitle, emailBody);
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.ToString());
                }
            }
官方微信
官方QQ群
31647020