3
votes

I am using ASP.NET Core 2.1 for creating an identity server. I use the Asp Identity and I scaffolded the login and register pages.

I have the following page:

[AllowAnonymous]
public class RegisterModel : PageModel
{
 ......
 public string ReturnUrl { get; set; }
 ......
 public void OnGet(string returnUrl = null)
 {
     ReturnUrl = returnUrl;
 }
 public async Task<IActionResult> OnPostAsync(string returnUrl = null)
 {
     returnUrl = returnUrl ?? Url.Content("~/");
     if (ModelState.IsValid)
     {
         return LocalRedirect(returnUrl);
     }

     return Page();
}

The cshtml contains:

@page
@model RegisterModel
......
<form asp-route-returnUrl="@Model.ReturnUrl" method="post">
......

Behaviour: I land on the page on this link: https://localhost:5028/Identity/Account/Register?returnUrl=testlink , so the ReturnUrl gets set to "testlink" in the OnGet() and is passed on to the form.

  1. Correct: If I create a user with no validation errors (ModelState is valid), then LocalRedirect(returnurl) gets called with "testlink".
  2. Wrong: If I create a user with validation errors (ModelState is invalid), then return Page() gets called. The issue is that in this case, the page is generated with empty model (@Model.ReturnUrl is null). The user sees the validation errors in the form, corrects them, but when he submits the form, he won't get redirected to "testlink" because it was lost.

My question: With what do I replace "return Page();" so that I can correct behaviour described on case 2? I tried "return LocalRedirect("/Identity/Account/Register?returnUrl=" + returnUrl)", but that refreshes the page (clears user input and doesn't show validation error messages).

Thank you!

2
Set the ReturnUrl property on POSTNkosi

2 Answers

6
votes

Set the ReturnUrl property on POST so it is available when the page reloads.

public IActionResult OnPost(string returnUrl = null) {
    returnUrl = returnUrl ?? Url.Content("~/");
    if (ModelState.IsValid) {
        return LocalRedirect(returnUrl);
    }
    //...if we get this far something went wrong.
    //reset properties on model so they appear when page reloads
    ReturnUrl = returnUrl;
    return Page();
}
0
votes

Before return Page(); call OnGet();

OnGet(your url); return Page();