Reputation: 377
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!
Upvotes: 0
Views: 1384
Reputation: 77876
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);
Upvotes: 3