Ram Iyer Ram Iyer - 2 months ago 29
ASP.NET (C#) Question

ASP.NET Web API 2 - User Registration Email Confirmation Fails

This is a Asp.Net WEB Api project. I am trying to get users register to the site and send an email to the users to confirm their email before granting access. I am able to register and generate the token for email confirmation but the callback url generation fails. Here is my code so far.

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;
}


It fails at the point where I generate the callbackurl. I get this exception:
"Value cannot be null.\r\nParameter name: routeCollection"

Stack Trace

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


Can someone please help?

Answer

Finally, got it working. I read up the documentation and got it working... Here is my code for those who are facing issues sending out emails in the context of Asp.Net Web API. SO examples that deal with similar issues in the context of MVC 5 web app were also helpful.

...
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());
                }
            }
Comments