├── src
├── Wei.TinyUrl.Api
│ ├── Startup.cs
│ ├── appsettings.json
│ ├── appsettings.Development.json
│ ├── Properties
│ │ └── launchSettings.json
│ ├── Program.cs
│ ├── Wei.TinyUrl.Api.csproj
│ ├── JsonConfigurationHelper.cs
│ ├── Controllers
│ │ └── HomeController.cs
│ └── ApplicationBuilderExtension.cs
├── Wei.TinyUrl.Data
│ ├── Wei.TinyUrl.Data.csproj
│ ├── TinyUrlDbContext.cs
│ ├── Entities
│ │ ├── Client.cs
│ │ └── UrlMapping.cs
│ ├── Util.cs
│ ├── Migrations
│ │ ├── 20191224035351_InitEntity.cs
│ │ ├── TinyUrlDbContextModelSnapshot.cs
│ │ └── 20191224035351_InitEntity.Designer.cs
│ └── Repositories
│ │ └── UrlMappingRepository.cs
└── Wei.TinyUrl.sln
├── README.md
├── LICENSE
└── .gitignore
/src/Wei.TinyUrl.Api/Startup.cs:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/a34546/Wei.TinyUrl/HEAD/src/Wei.TinyUrl.Api/Startup.cs
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/appsettings.json:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/a34546/Wei.TinyUrl/HEAD/src/Wei.TinyUrl.Api/appsettings.json
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/appsettings.Development.json:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/a34546/Wei.TinyUrl/HEAD/src/Wei.TinyUrl.Api/appsettings.Development.json
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Wei.TinyUrl.Data.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/TinyUrlDbContext.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using System;
3 | using System.Collections.Generic;
4 | using System.Text;
5 | using Wei.Repository;
6 | using Wei.TinyUrl.Data.Entities;
7 |
8 | namespace Wei.TinyUrl.Data
9 | {
10 | public class TinyUrlDbContext : BaseDbContext
11 | {
12 | public TinyUrlDbContext(DbContextOptions options) : base(options)
13 | {
14 | }
15 | public DbSet UrlMapping { get; set; }
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Wei.TinyUrl
2 | 基于.NetCore3.0 + Mysql开发的短网址项目
3 | 
4 |
5 | ## 快速开始
6 | **1. 修改连接字符串**
7 | - appsettings.Development.json中ConnectionStrings修改为自己的mysql连接
8 |
9 | **2. 更新数据库**
10 | - 打开程序包管理器控制台
11 | - 选中Wei.TinyUrl.Data项目,执行 Update-Database命令
12 |
13 | **3. 启动项目**
14 | - 设置Wei.TinyUrl.Api为启动项目
15 | - F5运行项目
16 |
17 | **4. 生成短链接**
18 | - 浏览器输入 http://localhost:5000/api/create?url=https://github.com/a34546/Wei.TinyUrl.git&key=123456789
19 | - 访问生成的短链接
20 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Entities/Client.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Text;
4 |
5 | namespace Wei.TinyUrl.Data.Entities
6 | {
7 | public class Client
8 | {
9 | ///
10 | /// 名称
11 | ///
12 | public string Name { get; set; }
13 |
14 | ///
15 | /// key
16 | ///
17 | public string Key { get; set; }
18 |
19 | ///
20 | /// 有效天数,为null时,可永久访问
21 | ///
22 | public int? Days { get; set; }
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/Properties/launchSettings.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "http://json.schemastore.org/launchsettings.json",
3 | "iisSettings": {
4 | "windowsAuthentication": false,
5 | "anonymousAuthentication": true,
6 | "iisExpress": {
7 | "applicationUrl": "http://localhost:50163",
8 | "sslPort": 0
9 | }
10 | },
11 | "profiles": {
12 | "Wei.TinyUrl.Api": {
13 | "commandName": "Project",
14 | "launchBrowser": true,
15 | "launchUrl": "",
16 | "applicationUrl": "http://localhost:5000",
17 | "environmentVariables": {
18 | "ASPNETCORE_ENVIRONMENT": "Development"
19 | }
20 | }
21 | }
22 | }
23 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/Program.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Hosting;
6 | using Microsoft.Extensions.Configuration;
7 | using Microsoft.Extensions.Hosting;
8 | using Microsoft.Extensions.Logging;
9 |
10 | namespace Wei.TinyUrl.Api
11 | {
12 | public class Program
13 | {
14 | public static void Main(string[] args)
15 | {
16 | CreateHostBuilder(args).Build().Run();
17 | }
18 |
19 | public static IHostBuilder CreateHostBuilder(string[] args) =>
20 | Host.CreateDefaultBuilder(args)
21 | .ConfigureWebHostDefaults(webBuilder =>
22 | {
23 | webBuilder.UseStartup();
24 | });
25 | }
26 | }
27 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/Wei.TinyUrl.Api.csproj:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | netcoreapp3.0
5 |
6 |
7 |
8 |
9 |
10 | all
11 | runtime; build; native; contentfiles; analyzers; buildtransitive
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Entities/UrlMapping.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.ComponentModel.DataAnnotations;
4 | using System.Text;
5 | using Wei.Repository;
6 |
7 | namespace Wei.TinyUrl.Data.Entities
8 | {
9 | public class UrlMapping : Entity
10 | {
11 | ///
12 | /// 生成的短链接Code
13 | ///
14 | [StringLength(10)]
15 | public string Code { get; set; }
16 |
17 | ///
18 | /// 需要转换的链接
19 | ///
20 | [StringLength(2000)]
21 | public string Url { get; set; }
22 |
23 | ///
24 | /// 过期时间(为null时是永久)
25 | ///
26 | public DateTime? ExpiryTime { get; set; }
27 |
28 | ///
29 | /// 来源
30 | ///
31 | [StringLength(20)]
32 | public string Source { get; set; }
33 | }
34 | }
35 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Util.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Text;
5 |
6 | namespace Wei.TinyUrl.Data
7 | {
8 | public static class Utils
9 | {
10 | static readonly Random random = new Random();
11 | static readonly char[] charsArray = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".ToCharArray();
12 | static readonly int charsArrayLength = charsArray.Length;
13 |
14 | public static string GenerateCode(int length)
15 | {
16 | var result = new char[length];
17 |
18 | for (int i = 0; i < length; i++)
19 | {
20 | result[i] = charsArray[random.Next(charsArrayLength)];
21 | }
22 |
23 | return new string(result);
24 | }
25 |
26 | public static bool HasValue(this IEnumerable source)
27 | {
28 | if (source != null && source.Any()) return true;
29 | return false;
30 | }
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2019 a34546
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/JsonConfigurationHelper.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.Extensions.Configuration;
2 | using Microsoft.Extensions.Configuration.Json;
3 | using Microsoft.Extensions.DependencyInjection;
4 | using Microsoft.Extensions.Options;
5 | using System;
6 | using System.Collections.Generic;
7 | using System.IO;
8 | using System.Linq;
9 | using System.Threading.Tasks;
10 |
11 | namespace Wei.TinyUrl.Api
12 | {
13 | public class JsonConfigurationHelper
14 | {
15 | public static T GetAppSettings(string key, string path = "appsettings.json") where T : class, new()
16 | {
17 | var currentClassDir = Directory.GetCurrentDirectory();
18 | IConfiguration config = new ConfigurationBuilder()
19 | .SetBasePath(currentClassDir)
20 | .Add(new JsonConfigurationSource { Path = path, Optional = false, ReloadOnChange = true })
21 | .Build();
22 | var appconfig = new ServiceCollection()
23 | .AddOptions()
24 | .Configure(config.GetSection(key))
25 | .BuildServiceProvider()
26 | .GetService>()
27 | .Value;
28 | return appconfig;
29 | }
30 |
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.sln:
--------------------------------------------------------------------------------
1 |
2 | Microsoft Visual Studio Solution File, Format Version 12.00
3 | # Visual Studio Version 16
4 | VisualStudioVersion = 16.0.29418.71
5 | MinimumVisualStudioVersion = 10.0.40219.1
6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Wei.TinyUrl.Data", "Wei.TinyUrl.Data\Wei.TinyUrl.Data.csproj", "{CE5531A1-0566-45A7-B501-10DA5175DC8E}"
7 | EndProject
8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Wei.TinyUrl.Api", "Wei.TinyUrl.Api\Wei.TinyUrl.Api.csproj", "{38688E27-FE56-4A42-AA51-456812A15AEF}"
9 | EndProject
10 | Global
11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution
12 | Debug|Any CPU = Debug|Any CPU
13 | Release|Any CPU = Release|Any CPU
14 | EndGlobalSection
15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution
16 | {CE5531A1-0566-45A7-B501-10DA5175DC8E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
17 | {CE5531A1-0566-45A7-B501-10DA5175DC8E}.Debug|Any CPU.Build.0 = Debug|Any CPU
18 | {CE5531A1-0566-45A7-B501-10DA5175DC8E}.Release|Any CPU.ActiveCfg = Release|Any CPU
19 | {CE5531A1-0566-45A7-B501-10DA5175DC8E}.Release|Any CPU.Build.0 = Release|Any CPU
20 | {38688E27-FE56-4A42-AA51-456812A15AEF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
21 | {38688E27-FE56-4A42-AA51-456812A15AEF}.Debug|Any CPU.Build.0 = Debug|Any CPU
22 | {38688E27-FE56-4A42-AA51-456812A15AEF}.Release|Any CPU.ActiveCfg = Release|Any CPU
23 | {38688E27-FE56-4A42-AA51-456812A15AEF}.Release|Any CPU.Build.0 = Release|Any CPU
24 | EndGlobalSection
25 | GlobalSection(SolutionProperties) = preSolution
26 | HideSolutionNode = FALSE
27 | EndGlobalSection
28 | GlobalSection(ExtensibilityGlobals) = postSolution
29 | SolutionGuid = {0CAA323A-2A5F-4598-AE00-5E81CA24F5D7}
30 | EndGlobalSection
31 | EndGlobal
32 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Migrations/20191224035351_InitEntity.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using Microsoft.EntityFrameworkCore.Metadata;
3 | using Microsoft.EntityFrameworkCore.Migrations;
4 |
5 | namespace Wei.TinyUrl.Data.Migrations
6 | {
7 | public partial class InitEntity : Migration
8 | {
9 | protected override void Up(MigrationBuilder migrationBuilder)
10 | {
11 | migrationBuilder.CreateTable(
12 | name: "UrlMapping",
13 | columns: table => new
14 | {
15 | Id = table.Column(nullable: false)
16 | .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
17 | CreateTime = table.Column(nullable: false),
18 | UpdateTime = table.Column(nullable: true),
19 | IsDelete = table.Column(nullable: false),
20 | DeleteTime = table.Column(nullable: true),
21 | Code = table.Column(maxLength: 10, nullable: true),
22 | Url = table.Column(maxLength: 2000, nullable: true),
23 | ExpiryTime = table.Column(nullable: true),
24 | Source = table.Column(maxLength: 20, nullable: true)
25 | },
26 | constraints: table =>
27 | {
28 | table.PrimaryKey("PK_UrlMapping", x => x.Id);
29 | });
30 | migrationBuilder.Sql("INSERT INTO `urlmapping` (`CreateTime`, `IsDelete`, `Code`, `Url`, `Source`) VALUES (now(), 0, 'WPysCS', 'http://www.baidu.com', 'test');");
31 | }
32 |
33 | protected override void Down(MigrationBuilder migrationBuilder)
34 | {
35 | migrationBuilder.DropTable(
36 | name: "UrlMapping");
37 | }
38 | }
39 | }
40 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/Controllers/HomeController.cs:
--------------------------------------------------------------------------------
1 | using System;
2 | using System.Collections.Generic;
3 | using System.Linq;
4 | using System.Threading.Tasks;
5 | using Microsoft.AspNetCore.Http;
6 | using Microsoft.AspNetCore.Mvc;
7 | using Microsoft.Extensions.Configuration;
8 | using Wei.TinyUrl.Data.Repositories;
9 |
10 | namespace Wei.TinyUrl.Api.Controllers
11 | {
12 | [Route("/")]
13 | [ApiController]
14 | public class HomeController : ControllerBase
15 | {
16 | readonly IUrlMappingRepository _urlMappingRepository;
17 | readonly string _serverUrl;
18 | public HomeController(IUrlMappingRepository urlMappingRepository,
19 | IConfiguration configuration)
20 | {
21 | _serverUrl = configuration.GetSection("ServerUrl").Value;
22 | _urlMappingRepository = urlMappingRepository;
23 | }
24 |
25 | [HttpGet()]
26 | public string Hello()
27 | {
28 | return $@"
29 | 生成短网址使用示例:
30 | GET:{_serverUrl}/api/create?url=http://www.baidu.com&key=123456789
31 | 返回结果:{_serverUrl}/WPysCS
32 | 测试key:123456789,有效期为1天
33 | ";
34 | }
35 |
36 | ///
37 | /// 生成短网址
38 | ///
39 | /// 需要生成的长网址
40 | /// 密匙
41 | ///
42 | [HttpGet("api/create")]
43 | public async Task GenerateTinyUrl(string url, string key)
44 | {
45 | if (string.IsNullOrEmpty(key)) return BadRequest("key is not null");
46 | if (string.IsNullOrEmpty(url)) return BadRequest("url is not null");
47 | if (!url.Contains(".")) return BadRequest("url is error");
48 | try
49 | {
50 | var code = await _urlMappingRepository.GenerateTinyUrl(url, key);
51 | return Ok($"{_serverUrl}/{code}");
52 | }
53 | catch (Exception ex)
54 | {
55 | return BadRequest(ex.Message);
56 | }
57 |
58 | }
59 | }
60 | }
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Migrations/TinyUrlDbContextModelSnapshot.cs:
--------------------------------------------------------------------------------
1 | //
2 | using System;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
6 | using Wei.TinyUrl.Data;
7 |
8 | namespace Wei.TinyUrl.Data.Migrations
9 | {
10 | [DbContext(typeof(TinyUrlDbContext))]
11 | partial class TinyUrlDbContextModelSnapshot : ModelSnapshot
12 | {
13 | protected override void BuildModel(ModelBuilder modelBuilder)
14 | {
15 | #pragma warning disable 612, 618
16 | modelBuilder
17 | .HasAnnotation("ProductVersion", "3.0.0")
18 | .HasAnnotation("Relational:MaxIdentifierLength", 64);
19 |
20 | modelBuilder.Entity("Wei.TinyUrl.Data.Entities.UrlMapping", b =>
21 | {
22 | b.Property("Id")
23 | .ValueGeneratedOnAdd()
24 | .HasColumnType("int");
25 |
26 | b.Property("Code")
27 | .HasColumnType("varchar(10) CHARACTER SET utf8mb4")
28 | .HasMaxLength(10);
29 |
30 | b.Property("CreateTime")
31 | .HasColumnType("datetime(6)");
32 |
33 | b.Property("DeleteTime")
34 | .HasColumnType("datetime(6)");
35 |
36 | b.Property("ExpiryTime")
37 | .HasColumnType("datetime(6)");
38 |
39 | b.Property("IsDelete")
40 | .HasColumnType("tinyint(1)");
41 |
42 | b.Property("Source")
43 | .HasColumnType("varchar(20) CHARACTER SET utf8mb4")
44 | .HasMaxLength(20);
45 |
46 | b.Property("UpdateTime")
47 | .HasColumnType("datetime(6)");
48 |
49 | b.Property("Url")
50 | .HasColumnType("varchar(2000) CHARACTER SET utf8mb4")
51 | .HasMaxLength(2000);
52 |
53 | b.HasKey("Id");
54 |
55 | b.ToTable("UrlMapping");
56 | });
57 | #pragma warning restore 612, 618
58 | }
59 | }
60 | }
61 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Migrations/20191224035351_InitEntity.Designer.cs:
--------------------------------------------------------------------------------
1 | //
2 | using System;
3 | using Microsoft.EntityFrameworkCore;
4 | using Microsoft.EntityFrameworkCore.Infrastructure;
5 | using Microsoft.EntityFrameworkCore.Migrations;
6 | using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
7 | using Wei.TinyUrl.Data;
8 |
9 | namespace Wei.TinyUrl.Data.Migrations
10 | {
11 | [DbContext(typeof(TinyUrlDbContext))]
12 | [Migration("20191224035351_InitEntity")]
13 | partial class InitEntity
14 | {
15 | protected override void BuildTargetModel(ModelBuilder modelBuilder)
16 | {
17 | #pragma warning disable 612, 618
18 | modelBuilder
19 | .HasAnnotation("ProductVersion", "3.0.0")
20 | .HasAnnotation("Relational:MaxIdentifierLength", 64);
21 |
22 | modelBuilder.Entity("Wei.TinyUrl.Data.Entities.UrlMapping", b =>
23 | {
24 | b.Property("Id")
25 | .ValueGeneratedOnAdd()
26 | .HasColumnType("int");
27 |
28 | b.Property("Code")
29 | .HasColumnType("varchar(10) CHARACTER SET utf8mb4")
30 | .HasMaxLength(10);
31 |
32 | b.Property("CreateTime")
33 | .HasColumnType("datetime(6)");
34 |
35 | b.Property("DeleteTime")
36 | .HasColumnType("datetime(6)");
37 |
38 | b.Property("ExpiryTime")
39 | .HasColumnType("datetime(6)");
40 |
41 | b.Property("IsDelete")
42 | .HasColumnType("tinyint(1)");
43 |
44 | b.Property("Source")
45 | .HasColumnType("varchar(20) CHARACTER SET utf8mb4")
46 | .HasMaxLength(20);
47 |
48 | b.Property("UpdateTime")
49 | .HasColumnType("datetime(6)");
50 |
51 | b.Property("Url")
52 | .HasColumnType("varchar(2000) CHARACTER SET utf8mb4")
53 | .HasMaxLength(2000);
54 |
55 | b.HasKey("Id");
56 |
57 | b.ToTable("UrlMapping");
58 | });
59 | #pragma warning restore 612, 618
60 | }
61 | }
62 | }
63 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Api/ApplicationBuilderExtension.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.AspNetCore.Builder;
2 | using Microsoft.AspNetCore.Http;
3 | using Microsoft.Extensions.Caching.Memory;
4 | using System;
5 | using System.Collections.Generic;
6 | using System.Linq;
7 | using System.Text.RegularExpressions;
8 | using System.Threading.Tasks;
9 | using Wei.TinyUrl.Data;
10 | using Wei.TinyUrl.Data.Entities;
11 | using Wei.TinyUrl.Data.Repositories;
12 |
13 | namespace Wei.TinyUrl.Api
14 | {
15 | public static class ApplicationBuilderExtension
16 | {
17 | public static IApplicationBuilder UseTinyUrl(this IApplicationBuilder builder)
18 | {
19 | return builder.UseMiddleware();
20 | }
21 |
22 | public static void LoadClients(this IApplicationBuilder builder)
23 | {
24 | var cache = (IMemoryCache)builder.ApplicationServices.GetService(typeof(IMemoryCache));
25 | var clients = JsonConfigurationHelper.GetAppSettings>("Clients");
26 | if (clients.HasValue()) clients.ForEach(x => cache.Set(x.Key, x));
27 | }
28 | }
29 |
30 | public class UrlMappingMiddleWare
31 | {
32 | private readonly RequestDelegate _next;
33 | public UrlMappingMiddleWare(RequestDelegate next)
34 | {
35 | _next = next;
36 | }
37 |
38 | public async Task Invoke(HttpContext context)
39 | {
40 | var path = context.Request.Path;
41 | if (path.HasValue)
42 | {
43 | var pathValue = path.Value;
44 | if (pathValue.StartsWith("/")) pathValue = pathValue.Substring(1);
45 | if (Regex.IsMatch(pathValue, @"^[a-zA-Z0-9]{6}$"))
46 | {
47 | var urlMappingRepository = (IUrlMappingRepository)context.RequestServices.GetService(typeof(IUrlMappingRepository));
48 | var longUrl = await urlMappingRepository.GetUrlByCode(pathValue);
49 | if (!string.IsNullOrEmpty(longUrl))
50 | {
51 | if (!Regex.IsMatch(longUrl, "(file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://", RegexOptions.IgnoreCase))
52 | {
53 | longUrl = "http://" + longUrl;
54 | }
55 | context.Response.Redirect(longUrl, true);
56 | return;
57 | }
58 | }
59 | }
60 | await _next.Invoke(context);
61 | }
62 | }
63 | }
64 |
--------------------------------------------------------------------------------
/src/Wei.TinyUrl.Data/Repositories/UrlMappingRepository.cs:
--------------------------------------------------------------------------------
1 | using Microsoft.EntityFrameworkCore;
2 | using Microsoft.Extensions.Caching.Memory;
3 | using System;
4 | using System.Collections.Generic;
5 | using System.Linq;
6 | using System.Text;
7 | using System.Threading.Tasks;
8 | using Wei.Repository;
9 | using Wei.TinyUrl.Data.Entities;
10 |
11 | namespace Wei.TinyUrl.Data.Repositories
12 | {
13 | public class UrlMappingRepository : Repository, IUrlMappingRepository
14 | {
15 | readonly IMemoryCache _cache;
16 | readonly IUnitOfWork _unitOfWork;
17 | public UrlMappingRepository(DbContext dbDbContext,
18 | IUnitOfWork unitOfWork,
19 | IMemoryCache cache) : base(dbDbContext)
20 | {
21 | _cache = cache;
22 | _unitOfWork = unitOfWork;
23 | }
24 |
25 | public async Task GenerateTinyUrl(string url, string key)
26 | {
27 | if (!_cache.TryGetValue(key, out Client client)) throw new Exception(" key is error");
28 | if (await QueryNoTracking().AnyAsync(x => x.Url.Equals(url, StringComparison.CurrentCultureIgnoreCase))) return (await QueryNoTracking().FirstOrDefaultAsync(x => x.Url == url))?.Code;
29 | var code = Utils.GenerateCode(6);
30 | while (!await IsUnique(code))
31 | {
32 | code = Utils.GenerateCode(6);
33 | }
34 | var entity = new UrlMapping { Code = code, Url = url, Source = client.Name };
35 | var now = DateTime.Now;
36 |
37 | if (client.Days.HasValue) entity.ExpiryTime = now.AddDays(client.Days.Value);
38 | await InsertAsync(entity);
39 | //清空已过期的链接
40 | HardDelete(x => x.ExpiryTime.HasValue && x.ExpiryTime.Value < now);
41 | await _unitOfWork.SaveChangesAsync();
42 | return entity.Code;
43 | }
44 |
45 | public async Task GetUrlByCode(string code)
46 | {
47 | var now = DateTime.Now;
48 | return (await QueryNoTracking(x => x.IsDelete == false).OrderByDescending(x => x.Id).FirstOrDefaultAsync(x => x.Code == code && (!x.ExpiryTime.HasValue || x.ExpiryTime.HasValue && x.ExpiryTime.Value > now)))?.Url;
49 | }
50 |
51 | private async Task IsUnique(string code)
52 | {
53 | var now = DateTime.Now;
54 | if (await QueryNoTracking().AnyAsync(x => x.Code == code && x.IsDelete == false && (!x.ExpiryTime.HasValue || x.ExpiryTime.HasValue && x.ExpiryTime.Value > now))) return false;
55 | return true;
56 | }
57 | }
58 |
59 | public interface IUrlMappingRepository : IRepository
60 | {
61 | ///
62 | /// 生成短链接
63 | ///
64 | Task GenerateTinyUrl(string url, string key);
65 |
66 | ///
67 | /// 根据Code获取长链接
68 | ///
69 | Task GetUrlByCode(string code);
70 | }
71 | }
72 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore Visual Studio temporary files, build results, and
2 | ## files generated by popular Visual Studio add-ons.
3 | ##
4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
5 |
6 | # User-specific files
7 | *.rsuser
8 | *.suo
9 | *.user
10 | *.userosscache
11 | *.sln.docstates
12 |
13 | # User-specific files (MonoDevelop/Xamarin Studio)
14 | *.userprefs
15 |
16 | # Mono auto generated files
17 | mono_crash.*
18 |
19 | # Build results
20 | [Dd]ebug/
21 | [Dd]ebugPublic/
22 | [Rr]elease/
23 | [Rr]eleases/
24 | x64/
25 | x86/
26 | [Aa][Rr][Mm]/
27 | [Aa][Rr][Mm]64/
28 | bld/
29 | [Bb]in/
30 | [Oo]bj/
31 | [Ll]og/
32 | [Ll]ogs/
33 |
34 | # Visual Studio 2015/2017 cache/options directory
35 | .vs/
36 | # Uncomment if you have tasks that create the project's static files in wwwroot
37 | #wwwroot/
38 |
39 | # Visual Studio 2017 auto generated files
40 | Generated\ Files/
41 |
42 | # MSTest test Results
43 | [Tt]est[Rr]esult*/
44 | [Bb]uild[Ll]og.*
45 |
46 | # NUnit
47 | *.VisualState.xml
48 | TestResult.xml
49 | nunit-*.xml
50 |
51 | # Build Results of an ATL Project
52 | [Dd]ebugPS/
53 | [Rr]eleasePS/
54 | dlldata.c
55 |
56 | # Benchmark Results
57 | BenchmarkDotNet.Artifacts/
58 |
59 | # .NET Core
60 | project.lock.json
61 | project.fragment.lock.json
62 | artifacts/
63 |
64 | # StyleCop
65 | StyleCopReport.xml
66 |
67 | # Files built by Visual Studio
68 | *_i.c
69 | *_p.c
70 | *_h.h
71 | *.ilk
72 | *.meta
73 | *.obj
74 | *.iobj
75 | *.pch
76 | *.pdb
77 | *.ipdb
78 | *.pgc
79 | *.pgd
80 | *.rsp
81 | *.sbr
82 | *.tlb
83 | *.tli
84 | *.tlh
85 | *.tmp
86 | *.tmp_proj
87 | *_wpftmp.csproj
88 | *.log
89 | *.vspscc
90 | *.vssscc
91 | .builds
92 | *.pidb
93 | *.svclog
94 | *.scc
95 |
96 | # Chutzpah Test files
97 | _Chutzpah*
98 |
99 | # Visual C++ cache files
100 | ipch/
101 | *.aps
102 | *.ncb
103 | *.opendb
104 | *.opensdf
105 | *.sdf
106 | *.cachefile
107 | *.VC.db
108 | *.VC.VC.opendb
109 |
110 | # Visual Studio profiler
111 | *.psess
112 | *.vsp
113 | *.vspx
114 | *.sap
115 |
116 | # Visual Studio Trace Files
117 | *.e2e
118 |
119 | # TFS 2012 Local Workspace
120 | $tf/
121 |
122 | # Guidance Automation Toolkit
123 | *.gpState
124 |
125 | # ReSharper is a .NET coding add-in
126 | _ReSharper*/
127 | *.[Rr]e[Ss]harper
128 | *.DotSettings.user
129 |
130 | # TeamCity is a build add-in
131 | _TeamCity*
132 |
133 | # DotCover is a Code Coverage Tool
134 | *.dotCover
135 |
136 | # AxoCover is a Code Coverage Tool
137 | .axoCover/*
138 | !.axoCover/settings.json
139 |
140 | # Visual Studio code coverage results
141 | *.coverage
142 | *.coveragexml
143 |
144 | # NCrunch
145 | _NCrunch_*
146 | .*crunch*.local.xml
147 | nCrunchTemp_*
148 |
149 | # MightyMoose
150 | *.mm.*
151 | AutoTest.Net/
152 |
153 | # Web workbench (sass)
154 | .sass-cache/
155 |
156 | # Installshield output folder
157 | [Ee]xpress/
158 |
159 | # DocProject is a documentation generator add-in
160 | DocProject/buildhelp/
161 | DocProject/Help/*.HxT
162 | DocProject/Help/*.HxC
163 | DocProject/Help/*.hhc
164 | DocProject/Help/*.hhk
165 | DocProject/Help/*.hhp
166 | DocProject/Help/Html2
167 | DocProject/Help/html
168 |
169 | # Click-Once directory
170 | publish/
171 |
172 | # Publish Web Output
173 | *.[Pp]ublish.xml
174 | *.azurePubxml
175 | # Note: Comment the next line if you want to checkin your web deploy settings,
176 | # but database connection strings (with potential passwords) will be unencrypted
177 | *.pubxml
178 | *.publishproj
179 |
180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to
181 | # checkin your Azure Web App publish settings, but sensitive information contained
182 | # in these scripts will be unencrypted
183 | PublishScripts/
184 |
185 | # NuGet Packages
186 | *.nupkg
187 | # NuGet Symbol Packages
188 | *.snupkg
189 | # The packages folder can be ignored because of Package Restore
190 | **/[Pp]ackages/*
191 | # except build/, which is used as an MSBuild target.
192 | !**/[Pp]ackages/build/
193 | # Uncomment if necessary however generally it will be regenerated when needed
194 | #!**/[Pp]ackages/repositories.config
195 | # NuGet v3's project.json files produces more ignorable files
196 | *.nuget.props
197 | *.nuget.targets
198 |
199 | # Microsoft Azure Build Output
200 | csx/
201 | *.build.csdef
202 |
203 | # Microsoft Azure Emulator
204 | ecf/
205 | rcf/
206 |
207 | # Windows Store app package directories and files
208 | AppPackages/
209 | BundleArtifacts/
210 | Package.StoreAssociation.xml
211 | _pkginfo.txt
212 | *.appx
213 | *.appxbundle
214 | *.appxupload
215 |
216 | # Visual Studio cache files
217 | # files ending in .cache can be ignored
218 | *.[Cc]ache
219 | # but keep track of directories ending in .cache
220 | !?*.[Cc]ache/
221 |
222 | # Others
223 | ClientBin/
224 | ~$*
225 | *~
226 | *.dbmdl
227 | *.dbproj.schemaview
228 | *.jfm
229 | *.pfx
230 | *.publishsettings
231 | orleans.codegen.cs
232 |
233 | # Including strong name files can present a security risk
234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424)
235 | #*.snk
236 |
237 | # Since there are multiple workflows, uncomment next line to ignore bower_components
238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
239 | #bower_components/
240 |
241 | # RIA/Silverlight projects
242 | Generated_Code/
243 |
244 | # Backup & report files from converting an old project file
245 | # to a newer Visual Studio version. Backup files are not needed,
246 | # because we have git ;-)
247 | _UpgradeReport_Files/
248 | Backup*/
249 | UpgradeLog*.XML
250 | UpgradeLog*.htm
251 | ServiceFabricBackup/
252 | *.rptproj.bak
253 |
254 | # SQL Server files
255 | *.mdf
256 | *.ldf
257 | *.ndf
258 |
259 | # Business Intelligence projects
260 | *.rdl.data
261 | *.bim.layout
262 | *.bim_*.settings
263 | *.rptproj.rsuser
264 | *- [Bb]ackup.rdl
265 | *- [Bb]ackup ([0-9]).rdl
266 | *- [Bb]ackup ([0-9][0-9]).rdl
267 |
268 | # Microsoft Fakes
269 | FakesAssemblies/
270 |
271 | # GhostDoc plugin setting file
272 | *.GhostDoc.xml
273 |
274 | # Node.js Tools for Visual Studio
275 | .ntvs_analysis.dat
276 | node_modules/
277 |
278 | # Visual Studio 6 build log
279 | *.plg
280 |
281 | # Visual Studio 6 workspace options file
282 | *.opt
283 |
284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
285 | *.vbw
286 |
287 | # Visual Studio LightSwitch build output
288 | **/*.HTMLClient/GeneratedArtifacts
289 | **/*.DesktopClient/GeneratedArtifacts
290 | **/*.DesktopClient/ModelManifest.xml
291 | **/*.Server/GeneratedArtifacts
292 | **/*.Server/ModelManifest.xml
293 | _Pvt_Extensions
294 |
295 | # Paket dependency manager
296 | .paket/paket.exe
297 | paket-files/
298 |
299 | # FAKE - F# Make
300 | .fake/
301 |
302 | # CodeRush personal settings
303 | .cr/personal
304 |
305 | # Python Tools for Visual Studio (PTVS)
306 | __pycache__/
307 | *.pyc
308 |
309 | # Cake - Uncomment if you are using it
310 | # tools/**
311 | # !tools/packages.config
312 |
313 | # Tabs Studio
314 | *.tss
315 |
316 | # Telerik's JustMock configuration file
317 | *.jmconfig
318 |
319 | # BizTalk build output
320 | *.btp.cs
321 | *.btm.cs
322 | *.odx.cs
323 | *.xsd.cs
324 |
325 | # OpenCover UI analysis results
326 | OpenCover/
327 |
328 | # Azure Stream Analytics local run output
329 | ASALocalRun/
330 |
331 | # MSBuild Binary and Structured Log
332 | *.binlog
333 |
334 | # NVidia Nsight GPU debugger configuration file
335 | *.nvuser
336 |
337 | # MFractors (Xamarin productivity tool) working folder
338 | .mfractor/
339 |
340 | # Local History for Visual Studio
341 | .localhistory/
342 |
343 | # BeatPulse healthcheck temp database
344 | healthchecksdb
345 |
346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017
347 | MigrationBackup/
348 |
349 | # Ionide (cross platform F# VS Code tools) working folder
350 | .ionide/
351 |
--------------------------------------------------------------------------------