以下是一个简单的C#代码示例,用于创建短链接和重定向长链接:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace ShortLinkApi.Controllers
{
public class ShortLinkController : ApiController
{
private static Dictionary<string, string> links = new Dictionary<string, string>();
// POST api/shortlink
public IHttpActionResult Post([FromBody]string longLink)
{
// generate a short code
string code = GenerateCode();
// add the link to the dictionary
links[code] = longLink;
// return the short link
string shortLink = Request.RequestUri.AbsoluteUri + "/" + code;
return Ok(shortLink);
}
// GET api/shortlink/abc123
public IHttpActionResult Get(string id)
{
// check if the short code exists
if (!links.ContainsKey(id))
{
return NotFound();
}
// redirect to the long link
string longLink = links[id];
return Redirect(longLink);
}
private string GenerateCode()
{
const string chars = "abcdefghijklmnopqrstuvwxyz0123456789";
var random = new Random();
return new string(Enumerable.Repeat(chars, 6)
.Select(s => s[random.Next(s.Length)]).ToArray());
}
}
}
这个代码示例包含两个API方法:
POST api/shortlink:接收一个长链接作为输入,生成一个短代码并将其存储在字典中。然后返回短链接。
GET api/shortlink/{id}:接收一个短代码作为输入,查找字典中是否存在该代码。如果存在,则将用户重定向到长链接。
为了使用这个API,你需要在你的应用程序中配置一个路由,以便将请求发送到正确的控制器和操作中。例如,在全局.asax.cs文件中,你可以添加以下代码:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
然后,在WebApiConfig.cs文件中,你可以添加以下路由:
using System.Web.Http;
namespace ShortLinkApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "ShortLink",
routeTemplate: "api/shortlink/{id}",
defaults: new { controller = "ShortLink", id = RouteParameter.Optional }
);
}
}
}
这个路由将匹配 http://localhost:port/api/shortlink/{id} 格式的请求,并将其发送到 ShortLink 控制器中的相应操作中。
希望这可以帮助你开始创建你自己的短链接API
绝!