Rune
Rune

Reputation: 832

ASP.NET Core 5 route redirection

We have an ASP.NET Core 5 Rest API where we have used a pretty simple route:

[Route("api/[controller]")]

The backend is multi-tenant, but tenant-selection has been handled by user credentials.

Now we wish to add the tenant to the path:

[Route("api/{tenant}/{subtenant}/[controller]")]

This makes cross-tenant queries simpler for tools like Excel / PowerQuery, which unfortunately tend to store credentials per url

The problem is to redirect all existing calls to the old route, to the new. We can assume that the missing pieces are available in the credentials (user-id is on form 'tenant/subtenant/username')

I had hope to simply intercept the route-parsing and fill in the tenant/subtenant route values, but have had not luck so far.

The closes thing so far is to have two Route-attributes, but that unfortunately messes up our Swagger documentation; every method will appear with and without the tenant path

Upvotes: 2

Views: 253

Answers (1)

Noah Stahl
Noah Stahl

Reputation: 7623

If you want to transparently change the incoming path on a request, you can add a middleware to set Path to a new value, for example:

app.Use(async (context,next) =>
{
    var newPath = // Logic to determine new path

    // Rewrite and continue processing
    context.Request.Path = newPath;

    await next();
});

This should be placed in the pipeline after you can determine the tenant and before the routing happens.

Upvotes: 2

Related Questions