0

I am about to rewrite a legacy PHP web api to ASP MVC. The calls to the legacy api are distinguished by the first query string param called 'function' with a variable amount of additional parameters based on the function parameter.

contoso.com/api.php?function=func1&param1=x&param2=y&...

I would now like to route those calls based on this param to different controller actions instead of having one action conditionally checking for the value of the 'function' param.

What would be the best way to achieve this?

nik
  • 1,471
  • 1
  • 12
  • 16

2 Answers2

1

You can make custom controller selector. Basicallly idea is that you first of all make handler that will route your request on your controller based on custom logic you have (for example your logic could be - if request has function parametar func1 then you should route your request on func1 controller.)

You make handler:

public class RouteSpecificHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        request.Properties["UseCustomSelector"] = true;
        return base.SendAsync(request, cancellationToken);
    }
}

You make controller selector:

public class CustomSelector : DefaultHttpControllerSelector
{
    public CustomSelector(HttpConfiguration configuration) : base(configuration)
    {
    }

    public override HttpControllerDescriptor SelectController(HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey("UseCustomSelector") &&
            request.Properties["UseCustomSelector"] as bool? == true)
        {
            //your logic goes here
        }

        return base.SelectController(request);
    }
}



config.Routes.MapHttpRoute(
            name: "MyRoute",
            routeTemplate: "api/dummy/{id}",
            defaults: new {controller = "Dummy", id = RouteParameter.Optional},
            constraints: null,
            handler: new RouteSpecificHandler { InnerHandler = new HttpControllerDispatcher(config) }
            );

You can see more here: ASP.NET Web API custom IHttpControllerSelector for a single route

Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75
0
public async Task<IActionResult>api(string func1,string param1,string param2)
{
    //.....
}

Please try this.

102425074
  • 781
  • 1
  • 7
  • 23
  • That is what i try to avoid, because there are several 'functions' which would make this one controller action really messy. Instead i'd like to have multiple controller actions named by the possible values of the function parameter. – nik Sep 23 '19 at 09:08