Return url functionality - c#

I'm using ASP.NET Core MVC with C#.
I have a functionality on my Login controller to take a parameter called ReturnUrl. The Idea is, that if this is set when the user logs in then I can redirect them back to the page. Straight forward enough.
The code looks like this:
[HttpGet]
[AllowAnonymous]
public IActionResult Login(string returnUrl = null)
{
...
}
However, the login functionality is handled by MVC and the main content is using Angular (version 1 not 2). Routes in my app are (for example) http://localhost/#/location1.
If I hit my MVC login page with (again, just an example) http://localhost/Login/?returnUrl=http://localhost/#/location1, then all I get in my returnUrl parameter is http://localhost/. It drops anything from the # symbol onwards.
Any ideas how to stop the code automatically escaping at the # symbol and taking the full url as the returnUrl object?

if you notice in your browser's debug tools, the browser would not be sending this # and any text after it to the server, so the server wouldn't know about its existence at all.
So instead of something like below,
http://localhost/Login/?returnUrl=http://localhost/#location1
do this (note the encoding of # into %23 in the url)
http://localhost/Login/?returnUrl=http://localhost/%23location1

I have 2 ideas that might work for you:
try escaping the return url in the client vefore sending the request.
instead of string change the return url type to Uri object
[HttpGet]
[AllowAnonymous]
public IActionResult Login(Uri returnUrl = null)
{
...
}

Related

Redirect user to page in a different ASP.NET Core Razor web site

I have an ASP.NET Core 2.1 Razor app with two menu items that are active prior to login. I want to transfer (redirect?) to a different web site when either of the menu items is clicked. I've tried a Redirect, as shown below, but the current url is added to the string I specify.
public IActionResult OnGet()
{
string url = "www.google.com";
return Redirect(url);
}
How can I do this?
It didn't take long to get the answer that was right in front of me anyway. Thanks to CodeCaster and Chris Pratt. Using a fully-qualified URL does work correctly.
public IActionResult OnGet()
{
string url = "https://www.google.com";
return Redirect(url);
}

ASP.NET MVC can I add Request filter to track previous page?

I have ASP.NET MVC Project and I have some pages (let's call it Destination Page) that I can access from multiple pages. So I want to track which page redirects to Destination Page so I can return to it again.
I red about Request Filters .. Can I use it in my case?
Thanks in advance :)
Just pass a return URL in the query string. In other words instead of redirecting like:
return RedirectToAction("Destination");
Do:
return RedirectToAction("Destination", new { returnUrl = Request.RawUrl });
Of course, your "Destination" action needs to accept this as a param:
public ActionResult Destination(Foo otherParam, string returnUrl)
Then, when you're done with whatever you're doing in "Destination", redirect back via:
if (!String.IsNullOrWhiteSpace(returnUrl) && Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Fallback");
The IsLocalUrl check is to prevent query string tampering, by ensuring that the return URL is actually local (i.e. relative) to your site.
You can get the refering page using Request.UrlReferrer
otherwise save the last url in a session-variable
like
Session["returnUrl"] = Request.RawUrl;
URL Referrer is only populated by an actual client-click (anchor tag, button).
Not when you manually put it in the URL (which is what my JavaScript is doing).
The solution i am doing to have to with is to create a cookie on the whatever.aspx page, and read that cookie from the JavaScript before i redirect again.

Rewriting Url in ASP.Net MVC

I am struggling over this issue since yesterday.I am working on a web application which includes email service.Email includes 'link' to a certain page of that application.
Now:I have 2 scenarios:
1) If the user is logged in(in the application) already and he hit
the url he got in his email,the link will open perfectly.
2) If the user is not logged in(in the application) then the url
will not open and will redirect itself to the login page with the
functionality added in the BaseController.
*
Now what I want is when the user logs in after hitting the url and on
successfully login the user gets redirect to the link provided in the
Email.
*
for eg: If the user gets an email to the detail page of an employee,So on successfully login the user gets redirect to the Detail page of the employee.
Something like appending the redirecturl to the login page.
I think rewriting url is what I should be doing.
But I dont know how can I use that in this case.Help me out.
The default project template that comes with ASP.NET MVC 5 behaves exactly as you describe.
If you want to redirect to a custom login URL, reconfigure the LoginPath property of the CookieAuthenticationOptions object
LoginPath = new PathString("/Account/Login")
In the default template this is done in the Startup.Auth.cs class.
NOTE: If you are using an old version of ASP.NET MVC, the default project template behaved in the same way. But previously this was implemented using Forms Authentication, so in order to redirect to a custom login URL you would then have to set the loginUrl attribute of the <forms> tag in the Web.config file
By default if a user tries to access the authorized page when he is not authorized the automatically gets redirected to the log in page or the page which is configured in web.config file for the element. And you can see the query string returnUrl having the url that was tried to access initially get appended to the log in url.
To access the return url, include a new parameter as returnUrl and maintain the return url in a hidden field by model data to access on post back for redirection.
If the user is authenticated then on post back then redirect the user to the specified page what he intended to go for.
I don't remember exactly but few month ago I implemented similar functionality and i had to save returnUrl explicitly (due to MVC bug or something) - Refer this link
AccountController.cs - Snapshot
[HttpGet]
[AllowAnonymous]
public ActionResult Login(string returnUrl, string userName)
{
// You login method logic....
// Add this line to save the returnUrl value
ViewBag.ReturnUrl = returnUrl;
}
Login.cshtml - Snapshot
#using (Html.BeginForm("Login", "Account", FormMethod.Post ,new {ReturnUrl = ViewBag.ReturnUrl}))
{
<input type="hidden" name="ReturnUrl" value="#Request.QueryString["ReturnUrl"]" />
// .....
}
See if this helps in your case.

ASP.net MVC routing parameters

I have route which looks like this:
http://localhost:1936/user/someOne/##feed%233dbfc1b3-44b4-42b4-9305-4822ac151527
My routes are configured like this:
routes.MapRoute("Profile", "user/{userName}/{treningId}",
new { controller = "Profile", action = "Index", userName = UrlParameter.Optional, treningId = UrlParameter.Optional }
);
And Action in my controller like this:
public ActionResult Index(string username, string treningId)
{
//more code here
}
But I can't get this part: ##feed%233dbfc1b3-44b4-42b4-9305-4822ac151527, when I debugged code, I saw treningId was null.
My question is how can I get part of URL after ## ?
This is not possible as hashes are not included in the request; they are reserved for client-side use in URLs (typically to mark a specific location in/portion of a document).
You have two options. Either encode the hash character as %23:
%23%23feed%233dbfc1b3-44b4-42b4-9305-4822ac151527
Or use a different character/route.
You can't.
The browser doesn't send the stuff after the first # to the server at all (you can verify this by using the debugger in your browser to inspect the traffic between your browser and the server). That is because the # (hash) character carries special meaning in HTTP.
Why don't you just
use regular query parameters (so, something like http://localhost:1936/user/someOne?myparameter=feed%233dbfc1b3-44b4-42b4-9305-4822ac151527), or, alternatively,
choose another delimiter than "##".
The way you have your URL written, the browser would not submit any portion of the fragment identifier - the hash part of the URL. As such, your MVC app will never receive the value and thus will always have it as null.
To make that value available to MVC, escape the # to avoid them marking beginning of fragment portion of URL.

Logging in with a ReturnUrl pointing to a POST action: FAIL!

I have an Asp.Net MVC project with the typical forms authentication that redirects the user to a page upon successful login. If there is a ReturnUrl in the querystring it will redirect the user to the ReturnUrl.
Problem comes when a logged in user sits on a page long enough for their login to time out and then submits the form causing a post to the server. Since the user is now no longer authenticated it'll force the user to log in again. However the ReturnUrl would point to an action that only accepts the POST method and would throw an exception after being redirected.
Is there a work around for this?
You have to create an identical GET action and redirect it back to the form they were filling out. The problem is that the redirect to the ReturnUrl is doing a GET, not a POST, hence the error.
Example:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult SomeFormAction()
{
//redirect them back to the original form GET here
RedirectToAction(stuffhere);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SomeFormAction(FormCollection collection)
{
//this is your original POST
}

Categories