Problem migrating from web api 2 to .net 5 web api

Viewed 110

I'm migrating a midsize application built with asp.net web api 2 to .net 5 web api. The problem is that I have now refactored the controllers and found that the way that the parameters passed by the query string do not have the same behavior in the .net core for routes.

So my problem is that to be able to switch to .net 5 I need to keep these apis working as they are today, I am not able to change routes and parameters at this time. I have routes as in the example below and that return the error AmbiguousMatchException: The request matched multiple endpoints:

// GET: api/<ValuesController>
[HttpGet]
public IEnumerable<string> GetAll()
{
    return new string[] { "value1", "value2" };
}

// GET: api/<ValuesController>?message=world
[HttpGet]
public string GetMessage([FromQuery] string message)
{
    return $"Hello {message}";
}

This controller works with web api 2. I saw that there is a compatibility pack for migration but it was removed in .NET 5 (Microsoft.AspNet.Mvc.WebApiCompatShim). I even tried to use it but runtime errors occur when registering its use.

I would like to know if someone has been through this and managed to solve it successfully, I already researched a lot and the most I found was some people talking to use IActionConstraint but the examples I found were to define mandatory parameters, it didn't seem to fit my problem.

If anyone knows something that can put me in the direction of a solution I would appreciate it.

1 Answers

Not sure if you can do it automatically, but you could do this:

private IActionResult GetAll()
{
    return new string[] { "value1", "value2" };
}

[HttpGet]
public IActionResult GetMessage([FromQuery] string message)
{
    if(message == null)
        return GetAll();
    return $"Hello {message}";
}
Related