Tony
Tony

Reputation: 17657

How to redirect on ASP.Net Core Razor Pages

I am using the new Razor Pages in ASP.Net core 2
Now I need to redirect

I tried this, but the page does not redirect:

public class IndexModel : PageModel
{
    public void OnGet()
    {
        string url = "/.auth/login/aad?post_login_redirect_url=" + Request.Query["redirect_url"];

        Redirect(url);
    }
}

How to redirect?

Upvotes: 58

Views: 121947

Answers (5)

Luca Ziegler
Luca Ziegler

Reputation: 4164

You can use the IActionResult to return a redirection instead of the requested page.

public IActionResult OnGet()
{
     if (!Auth())
     {
         return new RedirectToPageResult("/Portal/Login");
     }
     return Page();
}

Upvotes: 46

paywand dlshad nejeeb
paywand dlshad nejeeb

Reputation: 77

you can use this directly in razor view.

    @{
if (!Context.Request.Path.Value.Contains("Identity/Account/UserMustChangePassword"))
{
     Context.Response.Redirect("Identity/Account/UserMustChangePassword");
}
}

Upvotes: 4

Shojaeddin
Shojaeddin

Reputation: 2073

You can do it with this code:

  public async Task OnGetAsync()
  {
    Response.Redirect("/Panel");
  }

Upvotes: 10

Erik Philips
Erik Philips

Reputation: 54636

You were very close. These methods need to return an IActionResult (or Task<IActionResult> for async methods) and then you need to return the redirect.

public IActionResult OnGet()
{
    string url = "/.auth/login/aad?post_login_redirect_url=" 
      + Request.Query["redirect_url"];

    return Redirect(url);
}

Razor pages documentation

However, you have a huge Open Redirect Attack because you aren't validating the redirect_url variable. Don't use this code in production.

Upvotes: 83

A K
A K

Reputation: 764

Same for pages without cs:

@page

@functions
{
    public IActionResult OnGet()
    {
        string url = "/.auth/login/aad?post_login_redirect_url=" 
          + Request.Query["redirect_url"];

        return Redirect(url);
    }
}

Upvotes: 8

Related Questions