Click here to Skip to main content
15,891,529 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I used Asp.Net Identity and I implemented reset password, I send a link to user Email to reset password.

Here is the code:

[HttpPost]
    [Route("ForgotPassword")]
    [AllowAnonymous]
    public async Task<IHttpActionResult> ForgotPassword(ForgotPasswordViewModel model)
    {
        if (ModelState.IsValid)
        {
            var user = await UserManager.FindByEmailAsync(model.Email);
            if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
            {
             return BadRequest("Either user does not exist or you have not confirmed your email.");
            }

            try
            {
                // Send an email with this link
                string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
                Url.Link("DefaultApi",
              new { controller = "Account/ConfirmEmail", userId = user.Id, code = code });

                  string callbackUrl = Url.Link("DefaultApi", 
                    new { controller = "Account/ManageAccount/reset-password", userId = user.Id, code = code });
                //string callbackUrl = Url.Link("Default", 
                  //  new { controller = "User/ManageAccount/reset-password", userId = user.Id, code = code });
                await UserManager.SendEmailAsync(user.Id, "Reset Password", 
                    "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
                return Ok();
            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }

        }

        return BadRequest();
    }

    // GET api/Account/ManageAccount
    [AcceptVerbs("GET")]
    [AllowAnonymous]
     [Route("ManageAccount")]
    public IHttpActionResult ManageAccount(string id)
    {
        if (! String.IsNullOrEmpty(id))
        {
            string page = id + ".html";

           return Redirect(page);
        }
        return Redirect("Login.html");
    }




    // POST: /Account/ResetPassword
    [HttpPost]
    [AllowAnonymous]
    [Route("ResetPassword")]
    public async Task<IHttpActionResult> ResetPassword(ResetPasswordViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        var user = await UserManager.FindByEmailAsync(model.Email);
        if (user == null)
        {
           // return Redirect("https://localhost:44342/Login.html");
        }
        var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
        if (result.Succeeded)
        {
            return Ok();
        }
        return InternalServerError();
    }



Here is webApiConfig:

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services
        // Configure Web API to use only bearer token authentication.
        config.SuppressDefaultHostAuthentication();
        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new
        System.Net.Http.Headers.MediaTypeHeaderValue("application/json"));
        config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));


        // Web API routes
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        var json = config.Formatters.JsonFormatter;
        json.SerializerSettings.PreserveReferencesHandling =
            Newtonsoft.Json.PreserveReferencesHandling.Objects;
        config.Formatters.Remove(config.Formatters.XmlFormatter);


    }
}


What I have tried:

In AccountController I tried this but it doesn't work:

[HttpGet]
[AllowAnonymous]
public async Task<IHttpActionResult> ManageAccount(string id)
{
    if (! String.IsNullOrEmpty(id))
    {
        string page = id + ".html";

       return Redirect(page);
    }
    return Redirect("Login.html");
}




Also,
[AcceptVerbs("GET")]
[AllowAnonymous]
[Route("ManageAccount/{id}")]
public async Task<IHttpActionResult> ManageAccount(string id)
{
    if (! String.IsNullOrEmpty(id))
    {
        string page =  id + ".html";

        return Redirect(page);
    }
    return Redirect("Login.html");
}


Here is the link sent to email:(Look at its format) !
C#
http://localhost:7524/api/Account/ManageAccount/reset-password?userId=1011&code=vbGi%2FzN0oFjw6RLlFVuBHiyEz2rH%2FNaO7tc5Y7Y47vzKKC5aNgx9yzZLbHtMD1%2BVZYCot1dvRZSLupPUYcxpCW%2FIl4cJwAIxVjVYA1kxrIjobdrXVqHNMXJmTF5u6cc%2FJdA0uDlQzNjoG4%2Fcjfl3ToRxarZokxI3VN8TEvt1I2M%3D

When I click on it I got:
Invalid URI: The format of the URI could not be determined.

What I need is call html page "with url that have userId and code authentication" from WebApi

I'm really stuck Could you please help?
Posted
Updated 12-Apr-19 7:22am
v11
Comments
ZurdoDev 10-Apr-19 12:02pm    
What are you trying to do?
Where are you stuck?
Member 12919448 10-Apr-19 12:21pm    
I'm trying to reset password.
I send an email with user id and code to reset password
after user click on that link the url has his id and code authentication, this page ask user for his new password. What I found didn't work for me, it show me that path didnn't exist, and the code I tried, show me HTTP Error 404.0 - Not Found
Nirav Prabtani 11-Apr-19 3:13am    
Have you followed Route (URL) pattern ?

Can you please mention the endpoint which you are targeting ?

1 solution

Are you trying to implement something like this? Forgot Password And Reset Password Link On Email In MVC[^]

Note that MVC and Web API is pretty much the same, except that MVC serves Views but the concept is the same.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900