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");
}
Share:
14,138
cozmin-calin
Author by

cozmin-calin

Updated on June 09, 2022

Comments

  • cozmin-calin
    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
      noobed almost 9 years
    • cozmin-calin
      cozmin-calin almost 9 years
      Yes, 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
      noobed almost 9 years
      if your link is not complete for example "/Home/Car/1" then you can safely append your application url base address
    • elolos
      elolos almost 9 years
      Why 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
    cozmin-calin almost 9 years
    RouteData.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
    Mukesh Kalgude almost 9 years
    want you check before redirect page?