Working with return url in asp.net core
It seems they changed it in .Net Core MVC
How it worked for me:
public async Task<IActionResult> Login(LoginViewModel model)
{
....... other codes
string returnUrl = HttpContext.Request.Query["returnUrl"];
if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction("Index", "Home");
}
And it works smoothly now!
you can use Events
to get the Request and redirect to what url you want like this sample.
services.ConfigureApplicationCookie(options => {
options.Events = new Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationEvents
{
OnRedirectToLogin = ctx =>
{
var requestPath = ctx.Request.Path;
if (requestPath.Value == "/Home/About")
{
ctx.Response.Redirect("/Home/UserLogin");
}
else if (requestPath.Value == "/Home/Contact")
{
ctx.Response.Redirect("/Home/AdminLogin");
}
return Task.CompletedTask;
}
};
});
see this link: How to redirect access denied login based on the URL on ASP.NET Core 2 Identity?
You're specifically setting the LoginPath on your authentication options. By default, it will always direct you there when you are unauthenticated, regardless of the resource you tried to reach. I believe you may have to replace or inherit/override some of the innards in order to have the LoginPath be dynamic based off of the resource you request. I'm not sure if dynamic LoginPaths are natively supported otherwise? I could be wrong.
On an unrelated security note, you should verify that the resource in the ReturnUrl is local to your application before attempting to use it, or even return the homepage of your app. Otherwise it's possible for a malformed URL to spoof the redirect location to an resource designed to mimic the real one in appearance, but with malicious intent.
if (Url.IsLocalUrl(returnUrl))
return Redirect(returnUrl);
else
return RedirectToAction("Index", "Home");