Search code examples
c#asp.net-coreresponse.redirectminimal-apisredirecttoroute

ASP.NET Core Minimal API redirect that changes uri


I've done a couple of hours of searching after some failed attempts, and I'm hoping someone can provide a little clarity.

In the olden days, response.Redirect could be used in a web application to cause the browser to load a new URL.

It looks like there are similar methods for Minimal APIs and other .NET Core web application code, but none that I've tried so far have caused the behavior I'm hoping for.

I have an endpoint that allows for retrieving an image by using a method that takes uri parameters (something like /image/[year]/[month]/[day]).

I have another method at /latest that will grab the latest image. I want to build a uri when /latest is called that looks like /image/[year]/[month]/[day] that matches whatever the most recent file is (no problem there) in /latest, and have a full redirect occur... i.e. if I open a browser and try to open /latest, it does a regular old 302-type redirect and see the new url in the address bar.

Is that a thing, or no? I don't have to do this, but it seems like it might be possible, and would make a few things in the app I'm building simpler.

RedirectToRoute is what I've beaten my self up with the most while experimenting. Is that the right method, or am I barking up the wrong tree? Is it even possible?


Solution

  • You can use Results/TypedResults's Redirect (the first one is basically an alias for the second one):

    app.MapGet("/latest", () =>
    {
        var year = ...;
        var month = ...;
        var day = ...;
        return Results.Redirect($"/image/{year}/{month}/{day}");
    });