Answered by:
MailMessage Activation page not redirecting

Question
-
User-1901014284 posted
Hi,
I have the below code which I use to register a user's account for login. The database side adds the user and the activation code into the relevant tables as required. When i open my email and click on the validate email link it sends me back to the Registration Page to add a new user again rather than to the User Activation page.
If have added my code below and made in Bold the line where I think the issue lies. I have tried numerous ways to get this to reduirect me to the activation page but with no luck. There is no error message to provide I am afraid just redirecting me to the User_Registration.aspx rather than as below User_Activation.aspx as I require.
using (MailMessage mm = new MailMessage("Myemail@email.com", txtEmail.Text))
{
mm.Subject = "Account Activation";
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("User_Activation.aspx", "User_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("Myemail@email.com", "MyPassword");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);Any help would be greatly appreciated.
Thanks in advance.
Jonny
Friday, April 5, 2019 11:22 AM
Answers
-
User475983607 posted
If this code is running on the registration page then the link will always be the registration page,
body += "<br /><br />Please click the following link to activate your account"; body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("User_Activation.aspx", "User_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
https://docs.microsoft.com/en-us/dotnet/api/system.uri.absoluteuri?view=netframework-4.7.2
Use the Request.Url property to build the URL as illustrated in the following SO post. .
https://stackoverflow.com/questions/1214607/how-can-i-get-the-root-domain-uri-in-asp-net
Also, in the future please use the code toolbar button {;} when posting code as it make the code easier to read.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, April 5, 2019 12:23 PM
All replies
-
User-943250815 posted
If you can please, provide some more info/code.
Right now, I can only speculate about permissions in web.config, like if is activation page is allowed by anonymousFriday, April 5, 2019 11:38 AM -
User-1901014284 posted
Hi jzero,
Thank you very much for you response, please see below full code as requested. In regards to my webconfig I do not have any setting/permission to allow anonymous, I have also added in the main core of the webconfig file below.
webconfig
configuration>
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
<add key="autoFormsAuthentication" value="false" />
<add key="owin:AutomaticAppStartup" value="false" />
<add key="enableSimpleMembership" value="false" />
</appSettings><system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.6.1">
</compilation>
<pages enableSessionState="true" />
<authentication mode="Forms">
<forms defaultUrl="~/Home.aspx" loginUrl="~/Login.aspx" slidingExpiration="true" timeout="2880"></forms>
</authentication>
<authorization>
</authorization>
</system.web>
<connectionStrings>
<add name="con" connectionString="Data Source=servername;Initial Catalog=DB;User ID=username;Password=password" providerName="System.Data.sqlClient" />
</connectionStrings>
<runtime>User Registration pages
User_Registration.aspx page
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Portal_User_Registration.aspx.cs" Inherits="ClientPortal.Portal_User_Registration" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<th colspan="3">
Registration
</th>
</tr>
<tr>
<td>
First Name
</td>
<td>
<asp:TextBox ID="TxtFirstName" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername" runat="server" />
</td>
</tr>
<tr>
<td>
Surname
</td>
<td>
<asp:TextBox ID="Txtsurname" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername" runat="server" />
</td>
</tr>
<tr>
<td>
Job Role
</td>
<td>
<asp:TextBox ID="Txtjobrole" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername" runat="server" />
</td>
</tr>
<tr>
<td>
Username
</td>
<td>
<asp:TextBox ID="txtUsername" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtUsername" runat="server" />
</td>
</tr>
<tr>
<td>
Password
</td>
<td>
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" ForeColor="Red" ControlToValidate="txtPassword" runat="server" />
</td>
</tr>
<tr>
<td>
Confirm Password
</td>
<td>
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" />
</td>
<td>
<asp:CompareValidator ErrorMessage="Passwords do not match." ForeColor="Red" ControlToCompare="txtPassword" ControlToValidate="txtConfirmPassword" runat="server" />
</td>
</tr>
<tr>
<td>
Email
</td>
<td>
<asp:TextBox ID="txtEmail" runat="server" />
</td>
<td>
<asp:RequiredFieldValidator ErrorMessage="Required" Display="Dynamic" ForeColor="Red"
ControlToValidate="txtEmail" runat="server" />
<asp:RegularExpressionValidator runat="server" Display="Dynamic" ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="txtEmail" ForeColor="Red" ErrorMessage="Invalid email address." />
</td>
</tr>
<tr>
<td>
</td>
<td>
<asp:Button Text="Submit" runat="server" OnClick="RegisterUser" />
</td>
<td>
</td>
</tr>
</table><h1><asp:Literal ID="ltMessage" runat="server" /></h1>
</div>
</form>
</body>
</html>User_Registration.aspx.cs page
protected void RegisterUser(object sender, EventArgs e)
{
int userId = 0;
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("InsertUser"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
string hashed = BCrypt.HashPassword(txtPassword.Text.Trim(), BCrypt.GenerateSalt(12));cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@FirstName", TxtFirstName.Text.Trim());
cmd.Parameters.AddWithValue("@Surname", Txtsurname.Text.Trim());
cmd.Parameters.AddWithValue("@JobRole", Txtjobrole.Text.Trim());
cmd.Parameters.AddWithValue("@Username", txtUsername.Text.Trim());
cmd.Parameters.AddWithValue("@Password", hashed);
cmd.Parameters.AddWithValue("@Email", txtEmail.Text.Trim());
cmd.Connection = con;
con.Open();
userId = Convert.ToInt32(cmd.ExecuteScalar());
con.Close();
}
}
string message = string.Empty;
switch (userId)
{
case -1:
message = "Username already exists.\\nPlease choose a different username.";
break;
case -2:
message = "Supplied email address has already been used.";
break;
default:
message = "Registration successful. Activation email has been sent.";
SendActivationEmail(userId);
break;
}
ClientScript.RegisterStartupScript(GetType(), "alert", "alert('" + message + "');", true);
}
}
private void SendActivationEmail(int userId)
{
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string activationCode = Guid.NewGuid().ToString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO UserActivation VALUES(@UserId, @ActivationCode)"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@UserId", userId);
cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
using (MailMessage mm = new MailMessage("Myemail@email.com", txtEmail.Text))
{
mm.Subject = "Account Activation";
string body = "Hello " + txtUsername.Text.Trim() + ",";
body += "<br /><br />Please click the following link to activate your account";
body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("User_Registration.aspx", "User_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
body += "<br /><br />Thanks";
mm.Body = body;
mm.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.office365.com";
smtp.EnableSsl = true;
NetworkCredential NetworkCred = new NetworkCredential("Myemail@email.com", "Mypassword");
smtp.UseDefaultCredentials = true;
smtp.Credentials = NetworkCred;
smtp.Port = 587;
smtp.Send(mm);
}
}
}
}User Activation Pages
UserActivation.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Portal_User_Activation.aspx.cs" Inherits="ClientPortal.Portal_User_Activation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1><asp:Literal ID="ltMessage" runat="server" /></h1>
</div>
</form>
</body>
</html>UserActivation.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
string activationCode = !string.IsNullOrEmpty(Request.QueryString["ActivationCode"]) ? Request.QueryString["ActivationCode"] : Guid.Empty.ToString();
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("DELETE FROM UserActivation WHERE ActivationCode = @ActivationCode"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ActivationCode", activationCode);
cmd.Connection = con;
con.Open();
int rowsAffected = cmd.ExecuteNonQuery();
con.Close();
if (rowsAffected == 1)
{
ltMessage.Text = "Activation successful.";
}
else
{
ltMessage.Text = "Invalid Activation code.";
}
}
}
}
}
}
}
}Again, thank you very much for your help.
Jonny
Friday, April 5, 2019 12:03 PM -
User475983607 posted
If this code is running on the registration page then the link will always be the registration page,
body += "<br /><br />Please click the following link to activate your account"; body += "<br /><a href = '" + Request.Url.AbsoluteUri.Replace("User_Activation.aspx", "User_Activation.aspx?ActivationCode=" + activationCode) + "'>Click here to activate your account.</a>";
https://docs.microsoft.com/en-us/dotnet/api/system.uri.absoluteuri?view=netframework-4.7.2
Use the Request.Url property to build the URL as illustrated in the following SO post. .
https://stackoverflow.com/questions/1214607/how-can-i-get-the-root-domain-uri-in-asp-net
Also, in the future please use the code toolbar button {;} when posting code as it make the code easier to read.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Friday, April 5, 2019 12:23 PM -
User-943250815 posted
Seems you have routing in place, if yes Request.Url.AbsoluteUri = "User_Registration" and not ""User_Registration.aspx" as you expect, so ends with same URL on mail.
Run in debug mode and inspect Request.Url.AbsoluteUri valueFriday, April 5, 2019 12:55 PM -
User-1901014284 posted
Thank you all very much, the help provided has helped me resolve my issue!
Thank you very much again.
Jonny
Friday, April 5, 2019 3:36 PM