最近有个客户要求开发一套短网址网站,小编现在都使用.net core进行网站开发了,以是厘厘思路,想想使用.net core 的中间件应该很容易实现。
1. 构建一个中间件,监测网站的响应状态,代码如下:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using NetCoreTFCMS.Domain.DbModel;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using TianFeng.FrameworkCore.DapperEx;
namespace NetCoreTFCMS.MiddleWare
{
public static class RequestIPExtensions
{
public static IApplicationBuilder UseWatchNoFound(this IApplicationBuilder builder)
{
return builder.UseMiddleware<WatchNoFoundMiddleWare>();
}
}
public class WatchNoFoundMiddleWare
{
private readonly RequestDelegate _next;
private readonly ILogger logger;
public WatchNoFoundMiddleWare(RequestDelegate next, ILoggerFactory loggerFactory)
{
_next = next;
logger = loggerFactory.CreateLogger<WatchNoFoundMiddleWare>();
}
public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
var path = context.Request.Path.ToString().Trim();
if (path.LastIndexOf("/") == 0)
{
var salt = path.Replace("/", "");
if (Regex.IsMatch(salt, @"^[a-zA-Z0-9]{6}$"))
{
var db = (IDbService)context.RequestServices.GetService(typeof(IDbService));
var model = await db.GetModelAsync<Link>(new { Salt = salt });
if (model != null)
{
if (!Regex.IsMatch(model.SiteUrl, "(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://", RegexOptions.IgnoreCase))
{
model.SiteUrl = "http://" + model.SiteUrl;
}
context.Response.Redirect(model.SiteUrl, true);
}
else
{
logger.LogInformation(salt + "无匹配网址");
}
}
}
}
}
}
2.在startup.cs中的 Configure(IApplicationBuilder app)中添加引用 该 中间件
app.UseWatchNoFound();
这样该中间件就会响应短网址的六位字符串,如果匹配则重定向至对应的网址。
具体的短网址生成,我想就很简单,这里就不多说了,如果有需要,大家可以咨询我。
更多精彩文章请关注我们的微信公众号FocusDotCore: