using Orleans.Runtime;
using OrleansExample;
var builder = WebApplication.CreateBuilder(args);
builder.Host.UseOrleans(static siloBuilder =>
{
siloBuilder.UseLocalhostClustering();
siloBuilder.AddMemoryGrainStorage(“urls”);
});
var app = builder.Build();
app.MapGet(“/”, static () => “Welcome to the URL shortener, powered by Orleans!”);
app.MapGet(“/shorten”,
static async (IGrainFactory grains, HttpRequest request, CustomUrl url) =>
{
var host = $”{request.Scheme}://{request.Host.Value}”;
// Create a unique, short ID
var shortenedRouteSegment = Guid.NewGuid().GetHashCode().ToString("X");
// Create and persist a grain with the shortened ID and full URL
var shortenerGrain =
grains.GetGrain<IUrlShortenerGrain>(shortenedRouteSegment);
await shortenerGrain.SetUrl(url);
// Return the shortened URL for later use
var resultBuilder = new UriBuilder(host)
{
Path = $"/go/{shortenedRouteSegment}"
};
return Results.Ok(resultBuilder.Uri);
});
app.MapGet(“/go/{shortenedRouteSegment:required}”,
static async (IGrainFactory grains, string shortenedRouteSegment) =>
{
// Retrieve the grain using the shortened ID and url to the original URL
var shortenerGrain =
grains.GetGrain(shortenedRouteSegment);
var url = await shortenerGrain.GetUrl();
return Results.Redirect(url.Value);
});
app.Run();