Reputation: 17657
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
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
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
Reputation: 2073
You can do it with this code:
public async Task OnGetAsync()
{
Response.Redirect("/Panel");
}
Upvotes: 10
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);
}
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
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