C# 创建短链接和重定向长链接

以下是一个简单的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


绝!
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值