Reputation: 779
I want to redirect a user to an external site, outside of my ASP.NET MVC application, through a simple anchor tag. The tricky part is, the user can enter the link himself.
<a href="@model.Url">up up and away!</a>
If the user enters: www.google.com
in a field (bad user), he is being redirected to http://www.example.com/page/www.google.com
.
which is totally understandable, he should use http://
in front of his link...
It works as expected if I hardcode the http://
in front of the link like so: <a href="http://@model.Url">up up and away!</a>
BUT if the user was to enter http://www.google.com
(good user), the browser redirects to http://http//www.google.com
which goes nowhere..
So now the question: Is there a helper or method or something that routes to an external site no matter if the link contains http://
or not? Something like @Url.ExternalLink(model.Url)
would be great.
I could write this myself, but no need to reinvent the wheel, right? So if the wheel exists, please provide the wheel! Thanks in advance!
Checked a bunch of links, but they didn't satisfy my needs of the variable user input (never trust a user!): How to properly encode links to external URL in MVC Razor , Redirect to external url from OnActionExecuting? , Why does Response.Redirect not redirect external URL? , url.Action open link in new window on ASP.NET MVC Page , ...
Upvotes: 1
Views: 1690
Reputation: 2258
Your use case is quite specific, MVC framework doesn't have any extension methods for this. You need to develop it by yourself. You have the following options:
UrlHelper
class - @Url.ExternalLink(model.Url)
HtmlHelper
- @Html.ExternalLinkFor(model => model.Url)
<a href="@model.Url">up up and away!</a>
will still be valid.Upvotes: 1
Reputation: 4202
You can easily extend UrlHelper with a method:
public static string ExternalLink(this UrlHelper helper, string uri)
{
if (uri.StartsWith("http://")) return uri;
return string.Format("http://{0}", uri);
}
Examples
@Url.ExternalLink("http://google.com")
@Url.ExternalLink("google.com")
Upvotes: 0