简体   繁体   中英

RedirectPermanent not redirecting to the url

I'm coding a simple URL shortener.

Everything is working, except the redirection.

Here is the code that tries to redirect:

public async Task<ActionResult> Click(string segment)
    {
        string referer = Request.UrlReferrer != null ? Request.UrlReferrer.ToString() : string.Empty;
        Stat stat = await this._urlManager.Click(segment, referer, Request.UserHostAddress);
        return this.RedirectPermanent(stat.ShortUrl.LongUrl);
    }

When I input a link that is shortened, like this http://localhost:41343/5d8a2a , it redirects me to http://localhost:41343/www.google.com.br instead of www.google.com.br.

EDIT

After checking the answer, it works. Here is the final snippet of code.

if (!stat.ShortUrl.LongUrl.StartsWith("http://") && !stat.ShortUrl.LongUrl.StartsWith("https://"))
            return this.RedirectPermanent("http://" + stat.ShortUrl.LongUrl);
        else
            return this.RedirectPermanent(stat.ShortUrl.LongUrl);

Thanks!

Instead of RedirectPermanent() try using Redirect() like below. The specified URL has to be a absolute URL else it will try to redirect to within your application.

You can check for existence of http:// and add it accordingly

if(!stat.ShortUrl.LongUrl.Contains("http://"))
  return Redirect("http://" + stat.ShortUrl.LongUrl);

(OR)

Use StartsWith() string function

if(!stat.ShortUrl.LongUrl.StartsWith()("http://"))
  return Redirect("http://" + stat.ShortUrl.LongUrl);

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