.net 重定向到ASP MVC中的url
我有一个action-result方法,里面是一个重定向URL。我的问题是,在执行重定向之前,如何检查url是否有效.net 重定向到ASP MVC中的url,.net,asp.net-mvc,asp.net-mvc-4,url-redirection,.net,Asp.net Mvc,Asp.net Mvc 4,Url Redirection,我有一个action-result方法,里面是一个重定向URL。我的问题是,在执行重定向之前,如何检查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
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");
}
谁能帮我举个例子吗?我在谷歌上搜索,但找不到任何帮助我的东西。谢谢你试试这个
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");
}
假设您尝试重定向到的url在MVC应用程序的控制下,您可以使用url helper 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 }
);
警告:您的示例代码可能不反映您的产品代码,但url不应以您的方式硬编码。当汽车不在部署环境中应用程序的根目录下时,这会发生爆炸。您可以使用HttpClient发送get请求,如下所示:
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.GetAsync("Cars/Model/1");
if (response.IsSuccessStatusCode)
{
// redirect here
}
}
你查过了吗?是的,我查过那个链接。这不是我所需要的,因为方法重定向可以具有以下表单/Home/Car/1中的链接作为参数。首先,我认为我可以对该url执行ping操作,但我没有主机。如果您的链接不完整,例如/Home/Car/1,那么您可以安全地附加应用程序url基本地址为什么需要检查url是否有效?它始终是一个内部相对URL还是可以是外部URL?一种简单的方法是使用HttpClient发送get请求并检查响应状态。RoutedData.Values[controller]。ToString返回当前控制器和相同的操作。我不需要检查我的url是否包含当前控制器,因为我可以将用户重定向到其他控制器中的其他位置。假设我在登录操作结果中的帐户控制器中,您写的是返回帐户和登录。要在重定向页面之前检查吗?