Pergunta

Eu encontrei o seguinte código para criar um tinyurl.com url:

http://tinyurl.com/api-create.php?url=http://myurl.com

Isto irá criar automaticamente uma url tinyurl. Existe uma maneira de fazer isso usando código, especificamente C # no ASP.NET?

Foi útil?

Solução

Você provavelmente deve adicionar um pouco de verificação de erros, etc, mas esta é provavelmente a maneira mais fácil de fazê-lo:

System.Uri address = new System.Uri("http://tinyurl.com/api-create.php?url=" + YOUR ADDRESS GOES HERE);
System.Net.WebClient client = new System.Net.WebClient();
string tinyUrl = client.DownloadString(address);
Console.WriteLine(tinyUrl);

Outras dicas

Depois de fazer mais algumas pesquisas ... me deparei com o seguinte código:

    public static string MakeTinyUrl(string url)
    {
        try
        {
            if (url.Length <= 30)
            {
                return url;
            }
            if (!url.ToLower().StartsWith("http") && !Url.ToLower().StartsWith("ftp"))
            {
                url = "http://" + url;
            }
            var request = WebRequest.Create("http://tinyurl.com/api-create.php?url=" + url);
            var res = request.GetResponse();
            string text;
            using (var reader = new StreamReader(res.GetResponseStream()))
            {
                text = reader.ReadToEnd();
            }
            return text;
        }
        catch (Exception)
        {
            return url;
        }
    }

parece que ele pode fazer o truque.

Tenha em mente se você está fazendo um aplicativo em larga escala, que você é fiação em uma dependência específica bonito de esquema de URL / API do TinyURL. Talvez eles tenham garantias sobre a sua URL não mudar, mas é vale a pena conferir

Você tem que chamar essa URL do seu código, em seguida, ler novamente a saída do servidor e processá-lo.

Tenha um olhar para o System.Net.WebClient classe, DownloadString (ou melhor: DownloadStringAsync ) parece ser o que você quer.

De acordo com a este artigo , você poderia implementá-lo como este:

public class TinyUrlController : ControllerBase
{
    Dictionary dicShortLohgUrls = new Dictionary();

    private readonly IMemoryCache memoryCache;

    public TinyUrlController(IMemoryCache memoryCache)
    {
        this.memoryCache = memoryCache;
    }

    [HttpGet("short/{url}")]
    public string GetShortUrl(string url)
    {
        using (MD5 md5Hash = MD5.Create())
        {
            string shortUrl = UrlHelper.GetMd5Hash(md5Hash, url);
            shortUrl = shortUrl.Replace('/', '-').Replace('+', '_').Substring(0, 6);

            Console.WriteLine("The MD5 hash of " + url + " is: " + shortUrl + ".");

            var cacheEntryOptions = new MemoryCacheEntryOptions().SetSlidingExpiration(TimeSpan.FromSeconds(604800));
            memoryCache.Set(shortUrl, url, cacheEntryOptions);

            return shortUrl;
        }
    }

    [HttpGet("long/{url}")]
    public string GetLongUrl(string url)
    {
        if (memoryCache.TryGetValue(url, out string longUrl))
        {
            return longUrl;
        }

        return url;
    }
}

Aqui minha versão da aplicação:

static void Main()
{
    var tinyUrl = MakeTinyUrl("https://stackoverflow.com/questions/366115/using-tinyurl-com-in-a-net-application-possible");

    Console.WriteLine(tinyUrl);

    Console.ReadLine();
}

public static string MakeTinyUrl(string url)
{
    string tinyUrl = url;
    string api = " the api's url goes here ";
    try
    {
        var request = WebRequest.Create(api + url);
        var res = request.GetResponse();
        using (var reader = new StreamReader(res.GetResponseStream()))
        {
            tinyUrl = reader.ReadToEnd();
        }
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp);
    }
    return tinyUrl;
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top