首页 > 代码库 > 缩短url-url短地址链接
缩短url-url短地址链接
之前给合作方二维码时隐藏的url过长,导致合作方提出在打印的时候打印不出来的问题,要求url长度在50字节内,所以写了缩短url功能。
var url = string.Format("{0}/Billing/ScanCode?TenantId={1}&BussinessType={2}&groupNumber={3}&DeviceId={4}", baseUrl, args.TenantId, (int)BussinessType.SyncTransaction, groupNumber, device.Id); //过长的url 优化成短url var creatShotUrl = string.Format("/Billing/ScanCode?TenantId={0}&BussinessType={1}&groupNumber={2}&DeviceId={3}", args.TenantId, (int)BussinessType.SyncTransaction, groupNumber, device.Id); var invoiceUrlRepository = RF.Concrete<InvoiceUrlRepository>(); InvoiceUrl model = new InvoiceUrl(); string id = CommonShortUrl.GetShorturl(creatShotUrl, 0); url = baseUrl + "/t?e=" + id;
再添加一个控制器
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Rafy.Domain; namespace DBI.SaaS.Web.Controllers { public class TController : Controller { // GET: InvoiceUrl /// <summary> /// 根据短url的key 获取 真实的url 并跳转 /// </summary> /// <param name="urlKey">短url的key</param> /// <returns></returns> [Route("c/{e:maxlength(15)}")] public ActionResult Index(string e) { if (!string.IsNullOrEmpty(e)) { long id = CommonShortUrl.UnShort(e); var invoiceUrlRepository = RF.Concrete<InvoiceUrlRepository>(); //查询 var q = new CommonQueryCriteria(); var model = invoiceUrlRepository.GetById(id); if (model == null) { return Content("不存在的url!"); } return Redirect(model.UrlValue); } else { return Content("参数错误!"); } } } }
缩短url控制器代码
using Rafy.Domain; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace DBI.SaaS.Web.Controllers { public class CommonShortUrl { static string Number = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; /// /// 压缩ID标识 /// /// /// public static string Short(long n) { string result = string.Empty; int l = Number.Length; while (n / l >= 1) { result = Number[(int)(n % l)] + result; n /= l; } result = Number[(int)n] + result; return result; } /// /// 还原ID标识 /// /// /// public static long UnShort(string s) { long result = 0; s = s.Trim(); int l = s.Length; int m = Number.Length; for (int x = 0; x < l; x++) { result += Number.IndexOf(s[l - 1 - x]) * (long)Math.Pow(m, x); } return result; } /// <summary> /// 简化 url /// </summary> /// <param name="paramUrl"></param> /// <returns></returns> public static string GetShorturl(string paramUrl,int urlType) { //过长的url 优化成短url var invoiceUrlRepository = RF.Concrete<InvoiceUrlRepository>(); InvoiceUrl insertModel = new InvoiceUrl(); insertModel.UrlValue = paramUrl; insertModel.UrlType = urlType; invoiceUrlRepository.Save(insertModel); return CommonShortUrl.Short(insertModel.Id); } } }
这样缩短后的url地址:http://www.***.com/t?e=***
缩短url-url短地址链接
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。