Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/asp.net-mvc/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 将用户重定向到外部站点_C#_Asp.net Mvc_Asp.net Mvc 4_Url - Fatal编程技术网

C# 将用户重定向到外部站点

C# 将用户重定向到外部站点,c#,asp.net-mvc,asp.net-mvc-4,url,C#,Asp.net Mvc,Asp.net Mvc 4,Url,我想通过一个简单的锚定标记将用户重定向到ASP.NET MVC应用程序之外的外部站点。棘手的是,用户可以自己输入链接 如果用户在字段(坏用户)中输入:www.google.com,他将被重定向到http://www.example.com/page/www.google.com。 这是完全可以理解的,他应该在他的链接前面使用http:// 如果我将链接前面的http://硬编码如下: 但是如果用户要输入http://www.google.com(好用户),浏览器重定向到http://http/

我想通过一个简单的锚定标记将用户重定向到ASP.NET MVC应用程序之外的外部站点。棘手的是,用户可以自己输入链接

如果用户在字段(坏用户)中输入:
www.google.com
,他将被重定向到
http://www.example.com/page/www.google.com
。 这是完全可以理解的,他应该在他的链接前面使用
http://

如果我将链接前面的
http://
硬编码如下:

但是如果用户要输入
http://www.google.com
(好用户),浏览器重定向到
http://http//www.google.com
这是一个无处可去的地方

那么现在的问题是:是否有一个助手、方法或东西可以路由到外部站点,无论链接是否包含
http://
?像
@Url.ExternalLink(model.Url)
这样的东西会很棒。 我可以自己写,但不需要重新发明轮子,对吗?因此,如果车轮存在,请提供车轮!提前谢谢

检查了一堆链接,但它们不能满足我对可变用户输入的需求(永远不要信任用户!): , , , ,…

您可以使用以下方法轻松扩展:

public static string ExternalLink(this UrlHelper helper, string uri)
{
    if (uri.StartsWith("http://")) return uri;
    return string.Format("http://{0}", uri);
}
例子

@Url.ExternalLink("http://google.com")
@Url.ExternalLink("google.com")

您的用例非常具体,MVC框架没有任何用于此的扩展方法。 你需要自己开发它。您有以下选项:

  • UrlHelper
    class-
    @Url.ExternalLink(model.Url)
  • HtmlHelper
    -
    @Html.ExternalLinkFor(model=>model.Url)
  • 由于url来自您的模型,您可以在传递到视图之前验证/修改它。在这种情况下,
    仍然有效
  • 将正则表达式验证器添加到用户在url中键入的视图中

  • 谢谢,这就是我想知道的,到时候我会自己开发的!