How to capture an Object in the route (Route) of the PUT in a controller?

1

is that I have a PUT and I want to capture the value of the field that I am going to update, but in the database in SQL_Variant , so to do it I have to send an object when sending it to the database , this is my PUT

[HttpPut("{empid}/{codigo}/{valor}")]
public async Task<IActionResult> Put(int empid, string codigo, [FromRoute]object valor)
{
    try
    {
        return Ok(await repository.UpdateAsync(empid, codigo, valor));
    }
    catch (Exception e)
    {
         return BadRequest(e.ToString());
    }
}

If I here [FromRoute]object valor change it to string or int it receives it correctly, but if I leave it in type Object Null will arrive and it does not help me, how do I capture an object from the Controller route? ?

    
asked by Wilmilcard 24.10.2018 в 18:52
source

1 answer

1

Define it as a string and it will receive all the types that you send, then within the code of the controller you can cast to see really what type it is

[HttpPut("{empid}/{codigo}/{valor}")]
public async Task<IActionResult> Put(int empid, string codigo, [FromRoute]string valor)
{
    try
    {
        object persistValor = valor;

        int numberValor;
        bool isNumeric = int.TryParse(valor, out numberValor);

        if(isNumeric)
        {
          persistValor = numberValor;
        }

        return Ok(await repository.UpdateAsync(empid, codigo, persistValor));
    }
    catch (Exception e)
    {
         return BadRequest(e.ToString());
    }
}

As you will see you must see what type it is to assign the string that arrives or the value that becomes a numeric if it is a number

You could see if it is resolved with a custom ModelBinding , but I see it difficult if the value you send in the url, maybe if you did it as part of the body of the put

    
answered by 24.10.2018 / 19:07
source