Matt
Matt

Reputation: 371

Redirect to URL in ASP.NET Core

I need some help. I have been working on a way to load a page from within the "program.cs" file created by VS 2017 and ASP.NET Razor, but I cannot work out how this is done. I have looked on the web to find the answer, but I cannot find anything that will work.

What I'm looking to do is, after a lookup, I need to load the page again with an added searchstring. I have all the code doing the lookup and cross-checking, but I'm unable to get the code to redirect to the page again with the added searchstring.

Response.Redirect("/machinery?MachineLocation=" + searchstring);

The above code will not work in "program.cs" or "startup.cs," but it will work in any "cshtml.cs" file.

I have tried to DI the HttpContext, but this keeps returning null. Any pointers would be great.

Upvotes: 36

Views: 76869

Answers (2)

Zeyad
Zeyad

Reputation: 626

Short answer, use:

return LocalRedirect(ReturnUrl);

Long answer (important for security purposes):

Looks like you are grabbing the url from the user, if that is the case, I do not recommend using return Redirect(ReturnUrl); by itself because this opens a channel for Open Redirect Vulnerability Attacks. Basically someone can have an anchor element somewhere (like in an advertisement or so) that directs the user to your login page with a query string parameter that is named ReturnUrl that points to their own malicious website. Another way is that the ReturnUrl query string will redirect the users from your login form to a malicious login form that looks exactly like yours and then they show the user that the password was incorrect, making them think that maybe they missed a letter or so, so the users attempt to login again, but this time they are actually submitting their credentials to the malicious login form not yours. The hacker will then redirect them to your website after submitting their credentials to your website so that they don't notice anything wrong, it will just seem to them that they mis-typed the password but on the second attempt, they logged in successfully. So using LocalRedirect() instead of Redirect() will check first if the return url is your own website's url, if not then the redirect fails and an exception is thrown. Another way to avoid the exception yet check for local url is to do the following:

if (Url.IsLocalUrl(ReturnUrl)) {
    return Redirect(ReturnUrl);
}

That will give you the same result without throwing the exception because you are checking first if the url belongs to your web application or not, before proceeding with the redirection

Upvotes: 32

Shadi Alnamrouti
Shadi Alnamrouti

Reputation: 13318

Redirecting from a controller to a full URL is done simply by:

return Redirect(stringFullUrl);

Upvotes: 58

Related Questions