Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect after confirmation in ASP.NET WEP API controller

I have web api account controller where I confirm an user email

    [System.Web.Http.AllowAnonymous]
    [System.Web.Http.HttpGet]
    [System.Web.Http.Route("ConfirmEmail", Name = "ConfirmEmailRoute")]
    public async Task<IHttpActionResult> ConfirmEmail(string userId = "", string code = "")
    {
        if (string.IsNullOrWhiteSpace(userId) || string.IsNullOrWhiteSpace(code))
        {
            ModelState.AddModelError("", "User Id and Code are required");
            return BadRequest(ModelState);
        }

        IdentityResult result = await this.AppUserManager.ConfirmEmailAsync(userId, code);

        if (result.Succeeded)
        {
            return Ok();
        }
        else
        {
            return GetErrorResult(result);
        }
    }
}

This method is called when user clicks the confirmation link from email. After that I want to redirect it to "ConfirmidSuccessfully" page

In MVC we could do it like:

return View("ConfirmidSuccessfully");

There are other ways to redirect like:

var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("/ConfirmidSuccessfully");
return response;

Actually there are 2 questions: Is it good to redirect from web api method according to WEB API, or there's better approach What is the most appropriate way to do it

like image 832
amplifier Avatar asked Jan 07 '23 04:01

amplifier


2 Answers

It is not a good practice to redirect to a view or a web page when you are using REST hence ASP.Net Web API.

Just return a successful status code to the client. Let the client do the redirection itself.

For example, if you are using an AngularJS App to connect with your Web API then after a call to email confirmation finished with success, redirect to the web page/view by using the web page URL you store in the client side.

[EDIT]

Based on your comment

I use angularjs, but the call to email confirmation comes from user's email, not from client.

Then you must generate the confirmation email on server side by making the host's url to be your Angular JS app host. e.g. myangularjsapp.com/emilconfirmation/token. Send an email with this URL to your user.

With URL like that the user is redirect from his email to your AngularJS App. When he hit the app you initialize a call to the ASP.Net Web API by retrieving the token from your AngularJS App url.

like image 70
CodeNotFound Avatar answered Jan 09 '23 17:01

CodeNotFound


Since you are returning IHttpActionResult, you can return redirect in the action and this is the preferable way:

return this.Redirect("/path/to/redirect");
like image 43
Ивайло Кенов Avatar answered Jan 09 '23 19:01

Ивайло Кенов