如何在运行时在ASP.Net Core中创建URL重写?

时间:2019-05-03 19:11:50

标签: c# asp.net-mvc asp.net-core url-rewriting asp.net-core-mvc

为创建调整大小的图像的本地磁盘缓存,我试图弄清楚如何在运行时创建URL重写。

类似这样的东西:

[Route("(images/{id}.jpg")]
public IActionResult ResizeImage(int id, int height, int width)
{
    string webRoot = _env.ContentRootPath;
    var file = System.IO.Path.Combine(webRoot, $"resizedimage{id}.jpg");
    //Pseudocode:
    UrlRewriter.DoMagic($"images/{id}.jpg?height={height}&width={width}", "/resizedimage{id}.jpg")
    return File(file, "image/jpeg");
}

客户请求/images/123.jpg?height=100&width=100 ...

我可以创建一个静态URL重写,将/images/123.jpg?height=100&width=100重写为/images/resizedimage.jpg(磁盘上已调整大小的图像),绕过操作方法(大概)。 >

如何使用上面的伪代码即时执行相同的操作?

注意:

  • 我不在乎第一个请求,该请求将命中该操作方法,并通过文件结果(如上所示)将图像提供给图像,仅后续请求发送到相同的url。

  • 我知道在启动时创建动态url重写的方法,但在运行时(我问的不是)

  • 是的,我可以将重定向返回到图像文件,这也非常有效-但它仍然是来自客户端的两个同步请求。

  • 需要ASP.Net Core 2 +

2 个答案:

答案 0 :(得分:3)

最简单的方法是将RewriteOptions注入控制器,然后向其中添加规则,但是RewriteOptions.Rules不是线程安全的。

您需要自定义规则和线程安全集合。这样的事情应该起作用:

启动:

public void ConfigureServices(IServiceCollection services)
{
    services.AddSingleton<ImageRewriteCollection>();
    // ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseRewriter(new RewriteOptions().Add(new ImageRewriteRule(app.ApplicationServices.GetService<ImageRewriteCollection>())));
    // ...
}

ImageRewriteCollection:

public class ImageRewriteCollection
{
    private ConcurrentDictionary<(int id, int width, int height), string> imageRewrites
        = new ConcurrentDictionary<(int id, int width, int height), string>();

    public bool TryAdd(int id, int width, int height, string path)
        => imageRewrites.TryAdd((id, width, height), path);

    public bool TryGetValue(int id, int width, int height, out string path)
        => imageRewrites.TryGetValue((id, width, height), out path);
}

ImageRewriteRule:

public class ImageRewriteRule : IRule
{
    private readonly ImageRewriteCollection rewriteCollection;
    private readonly Regex pathRegex = new Regex("^/images/(\\d+).jpg");

    public ImageRewriteRule(ImageRewriteCollection rewriteCollection)
    {
        this.rewriteCollection = rewriteCollection;
    }

    public void ApplyRule(RewriteContext context)
    {
        var request = context.HttpContext.Request;
        var pathMatch = pathRegex.Match(request.Path.Value);
        if (pathMatch.Success)
        {
            bool isValidPath = true;
            int id = int.Parse(pathMatch.Groups[1].Value);

            int width = 0;
            int height = 0;
            string widthQuery = request.Query["width"];
            string heightQuery = request.Query["height"];

            if (widthQuery == null || !int.TryParse(widthQuery, out width))
                isValidPath = false;

            if (heightQuery == null || !int.TryParse(heightQuery, out height))
                isValidPath = false;

            if (isValidPath && rewriteCollection.TryGetValue(id, width, height, out string path))
            {
                request.Path = path;
                context.Result = RuleResult.SkipRemainingRules;
            }
        }
    }
}

控制器:

private readonly ImageRewriteCollection rewriteCollection;

public HomeController(ImageRewriteCollection rewriteCollection)
{
    this.rewriteCollection = rewriteCollection;
}

[Route("images/{id}.jpg")]
public IActionResult ResizeImage(int id, int width, int height)
{
    rewriteCollection.TryAdd(id, width, height, "/resizedimagepath...");
    return File();
}

答案 1 :(得分:0)