简体   繁体   中英

Redirecting user to external site

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 , ...

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:

  1. Create extension method (as you mentioned) for UrlHelper class - @Url.ExternalLink(model.Url)
  2. Create extension method for HtmlHelper - @Html.ExternalLinkFor(model => model.Url)
  3. As url comes from your model you can validate/modify it before passing to View. In this case <a href="@model.Url">up up and away!</a> will still be valid.
  4. Add regex validator to a View where user types in url

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM