简体   繁体   中英

Receiving parameter in controller action

My legacy code have controller action like this

[HttpGet("GetCar")]
public ActionResult<MyCarResult> GetCar(string carId)
{
   ...
}

I don't know how to hit this with provided carId value, tried with postman but without success. If I leave carId value from the postman request the api gets hit successfully.

I guess my question is: Shouldn't this code be refactored like this in order to get carId as a param value

[HttpGet("GetCar/{carId:string}")]
public ActionResult<MyCarResult> GetCar(string carId)
{
    ...
}

You are in right spot but, what you should do is check the postman values, are they correct? If yes implement the functions you created in the right way.

It looks like you are trying to specify pattern that uses syntax for route constraints:string doesn't seem to be valid constraint. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-5.0#route-constraint-reference

Just specifying GetCar/{carId} is enough

Route http://+/api/GetCar/333

    [HttpGet("GetCar/{carId}")]
    public ActionResult<MyCarResult> GetCar([FromRoute]string carId)
    {
        ...
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM