Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller dependency injection from route parameter

I'm using attribute base routing in an ASP.Net Core 2 application and attempting to inject a parameter into a Controller based on the route.

When I use the example I get an exception with message: "Unable to resolve service for type 'System.String' while attempting to activate (My Controller type)"

[Route("api/agencies/{agencyId}/clients")]
public class ClientDataController : Controller
{
    public ClientDataController([FromRoute] string agencyId)
    {

    }

    [HttpGet]
    public void SomeAction()
    {
    }

}

Are you not able to use the FromRoute attribute in a controller constructor? Do I have something else obviously wrong?

like image 733
eoldre Avatar asked Oct 27 '17 17:10

eoldre


1 Answers

There is a way to insert the value from the class Route attribute. Use property instead of the constructor.

The Route attribute can be applied only to class and method. See the source code here. The FromRoute can be applied to parameters and properties. See code here.

Since the Route attribute is not applicable to the constructor, the DI will not be able to resolve the parameter and you will get an error.

On the class level, we can use the FromRoute on public property to fetch the value from the Route.

[Route("api/agencies/{agencyId}/clients")]
public class ClientDataController
{
    [FromRoute]
    public string agencyId { get; set; }

    [HttpGet]
    public string SomeAction()
    {
        return agencyId;
    }

}
like image 55
Ripal Barot Avatar answered Sep 30 '22 09:09

Ripal Barot