以下是一个使用ASP.NET MVC框架创建URL缩短器的示例解决方案:
using System.ComponentModel.DataAnnotations;
public class UrlShortener
{
[Key]
public int Id { get; set; }
[Required]
public string OriginalUrl { get; set; }
[Required]
public string ShortenedUrl { get; set; }
}
using System;
using System.Linq;
using System.Web.Mvc;
public class UrlShortenerController : Controller
{
private ApplicationDbContext db = new ApplicationDbContext();
public ActionResult Index()
{
var urls = db.UrlShorteners.ToList();
return View(urls);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create(UrlShortener urlShortener)
{
if (ModelState.IsValid)
{
urlShortener.ShortenedUrl = GenerateShortUrl();
db.UrlShorteners.Add(urlShortener);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(urlShortener);
}
public ActionResult Redirect(string shortenedUrl)
{
var url = db.UrlShorteners.FirstOrDefault(u => u.ShortenedUrl == shortenedUrl);
if (url != null)
{
return Redirect(url.OriginalUrl);
}
return RedirectToAction("Index");
}
private string GenerateShortUrl()
{
// 实现自定义的URL缩短算法
// 返回一个唯一的短URL
}
}
@model List
@foreach (var url in Model)
{
Original URL: @url.OriginalUrl
Shortened URL: @Html.ActionLink(url.ShortenedUrl, "Redirect", new { shortenedUrl = url.ShortenedUrl })
}
@model UrlShortener
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.OriginalUrl)
@Html.TextBoxFor(model => model.OriginalUrl)
}
using System.Web.Mvc;
using System.Web.Routing;
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
// 其他配置代码
// 添加URL缩短器路由
RouteTable.Routes.MapRoute(
name: "Redirect",
url: "{shortenedUrl}",
defaults: new { controller = "UrlShortener", action = "Redirect" }
);
}
}
以上代码是一个基本的URL缩短器示例,可以根据实际需求进行修改和扩展。
上一篇:不同领域的不同分析器