在 .NET Core API 中实现 URL 短链接编码的过程,关键在于生成短链接、存储映射关系,并提供对外的 URL 编码和解码接口。以下是步骤和代码示例,展示了如何实现这一功能:

1. 创建模型

用于存储短链接与原始 URL 的映射。

namespace ShoppingCart.Models
{/// <summary>/// 短链接与原始 URL 的映射/// </summary>public class UrlMapping{/// <summary>/// 短链接/// </summary>public string ShortUrl { get; set; }/// <summary>/// 原始 URL/// </summary>public string OriginalUrl { get; set; }}
}

2. 生成短链接服务

主要通过一个计数器生成短链接,并与原始 URL 进行映射

using System.Text;
using System.Text.Json;
namespace ShoppingCart.Tools
{/// <summary>/// 生成短链接服务/// </summary>public class UrlShortenerService{private const string StorageFilePath = "urlMappings.json";// 存储映射的文件路径private const string BaseUrl = "http://short.ly/";private const string Characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";private int _counter;private Dictionary<string, string> _urlDictionary;public UrlShortenerService(){// 从文件加载映射_urlDictionary = LoadUrlMappings();_counter = _urlDictionary.Count > 0 ? _urlDictionary.Keys.Max(k => DecodeBase62(k.Substring(BaseUrl.Length))) + 1 : 0;}public string GenerateShortUrl(string originalUrl){// 如果已经有映射,则直接返回已存在的短链接if (_urlDictionary.ContainsValue(originalUrl)){return _urlDictionary.FirstOrDefault(x => x.Value == originalUrl).Key;}// 生成短链接var shortUrl = BaseUrl + EncodeBase62(_counter);_urlDictionary[shortUrl] = originalUrl;_counter++;// 将新的映射保存到文件SaveUrlMappings();return shortUrl;}public string GetOriginalUrl(string shortUrl){// 去掉短链接的 BaseUrl 部分,只保留后缀var shortUrlKey = shortUrl.Replace(BaseUrl, "");// 查找原始 URLreturn _urlDictionary.ContainsKey(BaseUrl + shortUrlKey) ? _urlDictionary[BaseUrl + shortUrlKey] : null;}// 编码数字为 Base62 字符串private string EncodeBase62(int number){var encodedString = new StringBuilder();while (number > 0){encodedString.Insert(0, Characters[number % 62]);number /= 62;}return encodedString.ToString();}// 解码 Base62 字符串为数字private int DecodeBase62(string shortUrl){int result = 0;foreach (char c in shortUrl){result = result * 62 + Characters.IndexOf(c);}return result;}// 从文件加载 URL 映射private Dictionary<string, string> LoadUrlMappings(){if (!File.Exists(StorageFilePath)){return new Dictionary<string, string>();}var json = File.ReadAllText(StorageFilePath);return JsonSerializer.Deserialize<Dictionary<string, string>>(json) ?? new Dictionary<string, string>();}// 将 URL 映射保存到文件private void SaveUrlMappings(){var json = JsonSerializer.Serialize(_urlDictionary);File.WriteAllText(StorageFilePath, json);}}
}

3. 创建 API 控制器

using Microsoft.AspNetCore.Mvc;
using ShoppingCart.Tools;namespace ShoppingCart.Controllers
{/// <summary>/// 集成生成短链接和获取原始 URL 的服务/// </summary>[ApiController][Route("api/[controller]")]public class UrlShortenerController : ControllerBase{private readonly UrlShortenerService _urlShortenerService;public UrlShortenerController(){_urlShortenerService = new UrlShortenerService();}// POST api/urlshortener/shorten[HttpPost("shorten")]public ActionResult<string> ShortenUrl([FromBody] string originalUrl){if (string.IsNullOrEmpty(originalUrl)){return BadRequest("Invalid URL");}var shortUrl = _urlShortenerService.GenerateShortUrl(originalUrl);return Ok(shortUrl);}// GET api/urlshortener/{shortUrl}[HttpGet("{shortUrl}")]public ActionResult<string> GetOriginalUrl(string shortUrl){var originalUrl = _urlShortenerService.GetOriginalUrl(shortUrl);if (originalUrl == null){return NotFound("Short URL not found");}return Ok(originalUrl);}}}


4. 配置 API 启动

var builder = WebApplication.CreateBuilder(args);// Add services to the container.
builder.Services.AddControllers();// Build the app
var app = builder.Build();// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{app.UseDeveloperExceptionPage();
}app.UseRouting();app.MapControllers();app.Run();

5. API 测试

.NET Core Api 中实现Url短链接编码_json

.NET Core Api 中实现Url短链接编码_短链接_02

返回短链接 http://short.ly/b


输入 b,返回 https://www.baidu.com

.NET Core Api 中实现Url短链接编码_短链接_03