How to route through URL parameter values instead of URL path values in ASP.NET Core 6 Web API?

59 Views Asked by At

On the client side, I can only request a URL address from the Web API, but I need to provide many different logic.

So, my Web API URL is

http://exampleDomain.com/ControllerDemo/HubActions?ActionName=(This url in client can't change)

When request url is

http://exampleDomain.com/ControllerDemo/HubActions?ActionName=ActionA

it should be routed to /ControllerDemo/ActionA

When request url is

http://exampleDomain.com/ControllerDemo/HubActions?ActionName=ActionB

it should be routed to /ControllerDemo/ActionB

1

There are 1 best solutions below

0
On BEST ANSWER

In your Program.cs (ImplicitUsings):

Just add custom middleware before app.UseRouting(), like this:

app.Use(async (context, next) =>
{
    if (context.Request.Path == "/ControllerDemo/HubActions")
        context.Request.Path = $"/ControllerDemo/{context.Request.Query["ActionName"]}";
    await next(context);
});

app.UseRouting();

See MSDN documentation:

The endpoint, if selected, can be retrieved from the HttpContext. Its properties can be inspected. Endpoint objects are immutable and cannot be modified after creation. The most common type of endpoint is a RouteEndpoint. RouteEndpoint includes information that allows it to be selected by the routing system.