Reputation: 421
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
Upvotes: 3
Views: 16865
Reputation: 4450
You can use HttpClient to send a get request like so:
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("Cars/Model/1");
if (response.IsSuccessStatusCode)
{
// redirect here
}
}
Upvotes: 0
Reputation: 2105
Assuming the url that you're trying to redirect to is under your MVC app's control, you can use the url helper Url.Action to guarantee that it is valid.
Url.Action("Model","Cars", new {id=1});
//should yield "Cars/Model/1 if your routing is configured to have id to be optional as below:
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Cars", action = "Model", id = UrlParameter.Optional }
);
Warning: Your sample code may not reflect your prod code but url should not be hard-coded in the way your have. This will blow up when "Cars" is not at the root of app in your deployment environment.
Upvotes: 0
Reputation: 4844
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");
}
Upvotes: 5