MVC3 URL作为参数

时间:2011-06-28 11:59:30

标签: c# asp.net-mvc asp.net-mvc-routing

我想创建一个接收URL作为参数的MVC应用程序。如何实现?

  1. 直接在网址上接收参数?
  2. 创建Get和Post方法,在内部将URL从Get one传递给Post one?
  3. 我尝试了第一个选项,但仍无法接收http://website/controller/method/http://otherurl.com

    等网址

    我是否必须创建一条新路线来实现这一目标?

    谢谢大家。

3 个答案:

答案 0 :(得分:2)

我建议您使用查询字符串参数,并确保该值正确地进行了网址编码:

http://website/controller/method?url=http%3A%2F%2Fotherurl.com

并在行动中:

public ActionResult Method(string url)
{
    // The url parameter here will equal to "http://otherurl.com"
    ...
}

答案 1 :(得分:0)

URL由两部分组成,第一部分是域(我认为),这里重要的是第二部分,称为查询字符串。 (第1部分是强制性的,第2部分不是)。

这是一个例子:

http://your-domain-here/stuff?page=1

现在page是一个查询字符串变量。您必须注意?分隔Url的两个部分,我没有在您的URL中看到一个,因此IMO,MVC路由引擎将尝试将整个Url与已注册的路由匹配(这不会被发现)。

不,我会说,您不必创建新路线,当我们需要新的“路径”时会创建新路线,但在您的情况下,您只需要改进URL以分隔离开查询字符串。

希望有所帮助。

答案 2 :(得分:0)

您必须创建另一条路线, 类似的东西:

routes.MapRoute( "UrlByParam", //Route Name
"{controller}/{action}/{url}", //Url Pattern
new { controller = "DefaultController", action = "DefaultAction" }); //Defaults

您还必须对您的网址进行编码, 所以,

http://website/controller/method/http://otherurl.com

会变成

http://website/controller/method/http%3A%2F%2Fotherurl.com