简体   繁体   中英

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?

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 .

You can use the IActionResult to return a redirection or your razor page.

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

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);
    }
}

You can do it with this code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM