A strongly typed URL generation library for ASP.NET Core
$ dotnet add package UriGenerationStrongly typed URL generation for ASP.NET Core:
_uriGenerator.GetUriByExpression<InvoicesController>(
httpContext,
c => c.GetInvoice(2));
If multiple URL paths match an action in your controller:
[HttpGet("api/invoices/{id}", Name = "ApiGetInvoice")]
[HttpGet("invoices/{id}", Name = "GetInvoice")]
public InvoiceResource GetInvoice(int id)
you can specify an endpoint name to generate an endpoint-specific URL:
_uriGenerator.GetUriByExpression<InvoicesController>(
httpContext,
c => c.GetInvoice(2),
"ApiGetInvoice");
_uriGenerator.GetUriByExpression<InvoicesController>(
httpContext,
c => c.GetInvoice(2),
"GetInvoice");
To further improve on this, you can use classes such as Microsoft.Azure.Management.ResourceManager.Fluent.Core.ExpandableStringEnum instead of strings to define your endpoint names. That would require you to write a simple adapter class that takes a string from your class and passes it to UriGenerator.
Extracting values from expression trees does introduce some overhead. To partially work around this problem, UriGeneration uses ASP.NET's CachedExpressionCompiler, so that equivalent route values' values' expression trees only have to be compiled once.
Additionally, it uses its internal Microsoft.Extensions.Caching.Memory.MemoryCache instance to cache extracted controller names, action names, and route values' keys within the scope of the application lifetime.
This means that, for example, on 2017 Surface Book 2 you are able to generate 100000 URLs in a second using a template like this: .
Install-Package UriGeneration
dotnet add package UriGeneration
builder.Services.AddUriGeneration();builder.Services.AddUriGeneration(o =>
{
o.SizeLimit = 100;
o.CompactionPercentage = 0.75;
});public class InvoicesController
{
private readonly IUriGenerator _uriGenerator;
public InvoicesController(IUriGenerator uriGenerator)
{
_uriGenerator = uriGenerator;
}
}To see the default log messages, enable LogLevel.Debug in the logging configuration.