短链接

using Microsoft.AspNetCore.Mvc;
using System;

namespace Feed.Controllers
{
    [ApiController]
    public class AaaController : Controller
    {
        [HttpGet]
        [Route("{url}")]
        public void GetBbb(string url)//短链接跳转
        {
            if (url == "1")
            {
                Response.Redirect("https://www.baidu.com", false);
            }
            else if (url == "2")
            {
                Response.Redirect("https://www.google.com", false);
            }
        }
        public static string GetShortUrl(string url)//短链接生成
        {
            string key = DateTime.Now.ToString();
            string[] chars = new string[]{
                 "a","b","c","d","e","f","g","h",
                 "i","j","k","l","m","n","o","p",
                 "q","r","s","t","u","v","w","x",
                 "y","z","0","1","2","3","4","5",
                 "6","7","8","9","A","B","C","D",
                 "E","F","G","H","I","J","K","L",
                 "M","N","O","P","Q","R","S","T",
                 "U","V","W","X","Y","Z"
            };

            var md5 = System.Security.Cryptography.MD5.Create();
            string hex = BitConverter.ToString(md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(key + url))).Replace("-", "");

            string[] resUrl = new string[4];
            for (int i = 0; i < 4; i++)
            {
                int hexint = 0x3FFFFFFF & Convert.ToInt32("0x" + hex.Substring(i * 8, 8), 16);
                string outChars = string.Empty;
                for (int j = 0; j < 6; j++)
                {
                    int index = 0x0000003D & hexint;
                    outChars += chars[index];
                    hexint >>= 5;
                }
                resUrl[i] = outChars;
            }
            return resUrl[new Random().Next(0, 3)];
        }
    }
}

 

posted @ 2022-03-07 16:39  邪不压正!  阅读(133)  评论(0编辑  收藏  举报