我有一个动作结果方法,里面正在做一个重定向(url)。我的问题是如何在进行重定向之前检查网址是否有效?
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");
}
任何人都可以帮我一个例子吗?我在谷歌搜索,但我找不到任何帮助我。感谢
答案 0 :(得分:2)
试试这个
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");
}
答案 1 :(得分:0)
假设您尝试重定向到的网址在MVC应用程序的控制之下,您可以使用网址助手Url.Action来保证其有效。
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 }
);
警告:您的示例代码可能无法反映您的产品代码,但网址不应以您的方式进行硬编码。当汽车"汽车"在部署环境中不是应用程序的根目录。
答案 2 :(得分:0)
您可以使用HttpClient发送get请求,如下所示:
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("Cars/Model/1");
if (response.IsSuccessStatusCode)
{
// redirect here
}
}