C#長短連結伺服器端WebApi作對映
阿新 • • 發佈:2020-08-20
[HttpGet] public IHttpActionResult GetLongLink(string code) { if (string.IsNullOrWhiteSpace(code)) { return Redirect(Request.RequestUri.AbsoluteUri.ToString() + "Home/Index");//跳轉到Home/index } var longlink = Redis.GetValue(code).Replace("\"", "");//取出來的帶有\"所以去掉它 if (string.IsNullOrWhiteSpace(longlink)) { return Json(new { error = 1, msg = "連結已經失效" }); } return Redirect(longlink); } [HttpGet] public IHttpActionResult GetShortLink(string longlink) {if (string.IsNullOrWhiteSpace(longlink)) { return Json(new { error = 1, msg = "長連結不能為空" }); } if (longlink.IndexOf("http://") != 0 && longlink.IndexOf("https://") != 0) { return Json(new { error = 1, msg = "長連結格式有誤" }); }var shortCode = Utils.ShortUrl(longlink)[0];//短網址演算法計算出的值拿第一個 Redis.SetValue(shortCode, longlink, DateTime.Now.AddDays(30)); var shortlink = Request.RequestUri.Authority.ToString() + "/" + shortCode;//拼接完整的連結(這裡不帶http不過沒啥影響,需要的話也可以拼上去) return Json(new { error = 0, msg = "成功", shortlink }); }