add page redirector for chorten-url service, u can use this feature, using this route: DOMAIN/?uri=SHORTED_URI

fix backend controller and change route to DOMAIN/r/SHORTED_URI
This commit is contained in:
Дмитрий Шиманский
2024-01-17 11:51:24 +03:00
parent 87e1f51e08
commit 152b5d8812
4 changed files with 39 additions and 11 deletions

View File

@@ -1,4 +1,4 @@
@page
@page "{uri?}"
@model IndexModel
@{
ViewData["Title"] = "yawaflua";

View File

@@ -1,22 +1,46 @@
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using yaflay.ru.Models;
using yaflay.ru.Models.Tables;
namespace yaflay.ru.Pages
{
public class IndexModel : PageModel
{
private readonly ILogger<IndexModel> _logger;
//public string? uri { get; set; } = null;
public IndexModel(ILogger<IndexModel> logger)
public IMemoryCache cache;
public AppDbContext ctx;
public string? uri { get; set; } = null;
public IndexModel(ILogger<IndexModel> logger, IMemoryCache cache, AppDbContext ctx)
{
_logger = logger;
this.cache = cache;
this.ctx = ctx;
}
public void OnGet(/**string? uri**/)
public void OnGet(string? uri)
{
Page();
//this.uri = uri ?? null;
this.uri = uri ?? null;
Console.WriteLine(uri);
if (this.uri != null)
{
Redirects? fromCache = cache.Get<Redirects>($"redirectsWithUrl-{uri}") ?? null;
if (fromCache == null)
{
fromCache = ctx.Redirects.FirstOrDefault(k => k.uri == uri);
Console.WriteLine("Im here!");
if (fromCache != null)
cache.Set($"redirectsWithUrl-{uri}", (object)fromCache, DateTime.Now.AddMinutes(10));
}
Console.WriteLine(fromCache?.ToString());
Response.Redirect(fromCache?.redirectTo ?? "/404");
}
else
{
Page();
}
}
}