Home > Back-end >  Map route parameters to model in asp.net core
Map route parameters to model in asp.net core

Time:02-03

I have an action with the following annotation,

[HttpGet("update/{hash}")]
public async Task<IActionResult> Update([FromQuery]Model model)
{
    // I need to use from model.Hash
    return Ok();
}

In addition, I have a simple model like below:

public class Model
{
    public string Hash { get; set; }
}

The model binder is not working, because that's clear the hash is not a queryString like ?hash=[value], it's an id.

I can not use another parameter to bind it like:

public async Task<IActionResult> Update(string hash)

because I have a validator for my model.

Is there any way in which I can bind hash to Hash my property?

CodePudding user response:

You can able to bind the route parameter to the model property by using [FromRoute(Name = "hash")] as shown in below.

public class Model
{
   [FromRoute(Name = "hash")]
   public string Hash { get; set; }
}

Refer this Microsoft doc

  •  Tags:  
  • Related