Redirect to url in ASP MVC
14,138
Try this
public ActionResult RedirectUser()
{
var url = "/Cars/Model/1"; //this is the url
var controller = RouteData.Values["controller"].ToString();
var action = RouteData.Values["action"].ToString();
if(controller=="car"&& action=="Model")
{
return this.Redirect(url);
}
else
{
return this.RedirectToAction("Index", "Home");
}
return this.RedirectToAction("Index", "Home");
}
Author by
cozmin-calin
Updated on June 09, 2022Comments
-
cozmin-calin almost 2 years
I have an action result method that inside is doing a Redirect(url). My question is how can I check that the url is valid before I do the redirect ?
public ActionResult RedirectUser() { var url = "/Cars/Model/1"; //this is the url // now i should check if the redirect return a 200 code (the url is valid) and if is valid I should redirect to that url, else i should redirect to "/Home/Index" if(this.Redirect(url)) { return this.Redirect(url); } else { return this.RedirectToAction("Index", "Home"); } return this.RedirectToAction("Index", "Home"); }
Can anyone help me with an example ? I search on google but I couldn't find anything to help me. Thanks
-
noobed almost 9 yearshave you checked stackoverflow.com/questions/7033428/…
-
cozmin-calin almost 9 yearsYes, I checked that link. It's not what I need because the method Redirect() could have as paramater the link in this form ("/Home/Car/1"). Firstly I thought that I could do a ping to that url but I don't have the host.
-
noobed almost 9 yearsif your link is not complete for example "/Home/Car/1" then you can safely append your application url base address
-
elolos almost 9 yearsWhy do you need to check if the URL works? Is it always going to be an internal (relative) URL or it could be external? One easy way to do this would be using HttpClient to send a get request and check the response status.
-
-
cozmin-calin almost 9 yearsRouteData.Values["controller"].ToString() is returning the current controller and the same for action. I dont need to check if my url contains the current controller because I can redirect the user to another location (in another controller). Let's say I'm in account controller in logIn action result, what you wrote there is return "account" and "logIn".
-
Mukesh Kalgude almost 9 yearswant you check before redirect page?