How To Activate Links After Sending Activation Link Email To User In MVC And Web API

Today, in this article, I will explain how to activate links after sending an email of an activation link to the user using MVC and Web API. I have explained in the previous article how to send activation link in an email after user inputs their registration details in MVC. When we activate the link, then the activation code matches with the one in our database. If matched, it will activate the profile; otherwise, it doesn't.

You can check this link to the previous article  

Before we start this discussion, let us remember some points regarding email sending functionality.

  1. First, we check that our email id should not have a 2-step verification added.
  2. Enable less secure apps to access accounts.

    • -> Sign in to your Gmail account.
    • ->Click Security > Basic settings.
    • ->Under Less secure apps, select Go to settings for less secure apps.
    • ->In the sub-window, select the "Allow users to manage their access to less secure apps" radio button.

So now, let us see the required steps.

Step 1

First, see the activation link we have sent in the previous article.

MVC

Step 2 

When clicking this link, first, it will go our RegsterUser Controller in MVC project and also, it will send the Controller name, Action method and parameter value, i.e., Activation code. 

MVC

 

Finally, we can see our code and also, we will call RunAsyncGet method which we created in RestClient Class.

  1. [System.Web.Mvc.HttpGet]  
  2.        public async Task<ActionResult> ActivateAccount(string id)  
  3.        {  
  4.            string str = "";  
  5.            RestClient restClient = new RestClient();  
  6.            string value = await restClient.RunAsyncGet<string, string>("api/UserReg/VeryFiyAccount", id);  
  7.   
  8.            if (value != null)  
  9.            {  
  10.                str = value;  
  11.            }  
  12.            else  
  13.            {  
  14.                str = "Activation falid";  
  15.            }  
  16.   
  17.            ViewBag.Message = str;  
  18.            return View();  
  19.   
  20.        }  

Now, right-click on ActicationAcount method and add a View for displaying a user-friendly message and write the below code.

  1. <link href="~/Content/bootstrap.css" rel="stylesheet" />  
  2. <div style="height:70%;margin:100px;padding:150px;border:2px solid green;box-shadow:yellow 2px inset;border-radius:10px;" align="center">  
  3.   
  4.     @if (ViewBag.Message != null)  
  5.     {  
  6.         <div class="alert alert-success">  
  7.             <strong>Success !</strong><b>@ViewBag.Message </b>  
  8.         </div>  
  9.     }  
  10.     else  
  11.     {  
  12.         <div class="alert alert-danger">  
  13.             <strong>Error!</strong>  
  14.         </div>  
  15.     }  
  16. </div>  

Here, we create a method RunAsyncGet in RestClient Class for consuming the API.

  1.  private HttpClient client;  
  2.        public const string ApiUri = "http://localhost:49619/";  
  3.        public const string MediaTypeJson = "application/json";  
  4.        public const string RequestMsg = "Request has not been processed";  
  5.        public static string ReasonPhrase { get; set; }  
  6.        public RestClient()  
  7.        {  
  8.            this.client = new HttpClient();  
  9.            this.client.BaseAddress = new Uri(ApiUri);  
  10.            this.client.DefaultRequestHeaders.Accept.Clear();  
  11.            this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(MediaTypeJson));  
  12.        }  
  13.   
  14. public async Task<U> RunAsyncGet<T, U>(dynamic uri, dynamic data)  
  15.        {  
  16.            HttpResponseMessage response = await this.client.GetAsync(uri + "/" + data);  
  17.            if (response.IsSuccessStatusCode)  
  18.            {  
  19.                return await response.Content.ReadAsAsync<U>();  
  20.            }  
  21.            else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest)  
  22.            {  
  23.                throw new ApplicationException(response.ReasonPhrase);  
  24.            }  
  25.            else if (response.StatusCode == System.Net.HttpStatusCode.BadGateway)  
  26.            {  
  27.                throw new Exception(response.ReasonPhrase);  
  28.            }  
  29.   
  30.            throw new Exception(RequestMsg);  
  31.        }  

Step 3

Note
When we write the method for consuming the service in the server side, then some time is needed to update the System.Net.Http.Formatting.Extension. So, for this, go to Tools >> NuGet Package Manager and then Package Manager console.

MVC

After that, we will write code for updating "Install-Package System.Net.Http.Formatting.Extension -Version 5.2.3" on console.

MVC

Step 4

After that, we will create a method in RegAPI Controller for creating the service.

  1. [HttpGet]  
  2.         [Route("VeryFiyAccount/{id}")]  
  3.         public string VeryfiyUserAccount(string id)  
  4.         {  
  5.             string str = "";  
  6.             try  
  7.             {  
  8.                 str = objReg.VeryFiyAccount(id);  
  9.             }  
  10.             catch (ApplicationException ex)  
  11.             {  
  12.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadRequest, ReasonPhrase = ex.Message });  
  13.             }  
  14.             catch (Exception ex)  
  15.             {  
  16.                 throw new HttpResponseException(new HttpResponseMessage { StatusCode = HttpStatusCode.BadGateway, ReasonPhrase = ex.Message });  
  17.             }  
  18.   
  19.             return str;  
  20.         }  

Step 5

Now, we will go to RegLogic class in a Business logic folder and write the below code. 

Before we write this logic, we will check in our database table that EmalVeryFyField is false.

MVC  
  1. public string VeryFiyAccount(string activationCode)  
  2.     {  
  3.   
  4.         string str = "";  
  5.         objEntity.Configuration.ValidateOnSaveEnabled = false;  
  6.         var value = objEntity.RegDetails.Where(a => a.ActivateionCode == new Guid(activationCode)).FirstOrDefault();  
  7.         if (value != null)  
  8.         {  
  9.             value.EmailIVeryFied = true;  
  10.             objEntity.SaveChanges();  
  11.             str = "Dear user, Your email successfully activated now you can able to login";  
  12.         }  
  13.         else  
  14.         {  
  15.             str = "Dear user, Your email not activated";  
  16.         }  
  17.   
  18.         return str;  
  19.   
  20.     }  

After that, we will get the final output.

MVC

We will check also in our database that emailVeryFyFied is true.

MVC