简体   繁体   中英

Dynamic property name in API input

I have an ASP.NET Core API that takes in a DTO parameter called DetParameterCreateDto which looks like this

DTO

public class DetParameterCreateDto
{
    public int Project_Id { get; set; }
    public string Username { get; set; }
    public string Instrument { get; set; }
    public short Instrument_Complete { get; set; }
}

The problem I am having is that the parameter passed in from the client has a property named Instrument_Complete ; which is dynamic.

The name is actually [instrument]_complete where [instrument] is the name of the instrument. So if the name of the instrument is my_first_project then the parameter's property name will actually be my_first_instrument_complete , which will not properly map to my API's input parameter; so it always shows a value of 0

API Method

    [HttpPost("create")]
    public IActionResult CreateDetEntry(DetParameterCreateDto detParameters)
    {
       // some stuff in here
    }

Update (8/2)

Using bradley's suggestion it seems like I can do this with custom model binding. However, I have to set each model property instead of just the one I want to set instrument_complete (and convert some from string). This does not seem like an optimal solution.

    public Task BindModelAsync(ModelBindingContext bindingContext)
    {
        if (bindingContext == null)
        {
            throw new ArgumentNullException(nameof(bindingContext));
        }

        var instrumentValue = bindingContext.ValueProvider.GetValue("instrument").FirstValue;

        var model = new DetParameterCreateDto()
        {
            Project_Id = Convert.ToInt32(bindingContext.ValueProvider.GetValue("project_id").FirstValue),
            Username = bindingContext.ValueProvider.GetValue("username").FirstValue,
            Instrument = instrumentValue,
            Instrument_Complete = Convert.ToInt16(bindingContext.ValueProvider.GetValue($"{instrumentValue}_complete").FirstValue),

        bindingContext.Result = ModelBindingResult.Success(model);
        return Task.CompletedTask;

    }

DTO params in Web API are limiting especially when the properties are dynamic. I solved a similar issue before by using JObject . Yours could be something like:

[HttpPost("create")]
public IActionResult CreateDetEntry(JObject detParameters)
{
    //DO something with detParameters
    ...
    //Optionally convert it to your DTO
    var data = detParameters.ToObject<DetParameterCreateDto>();
   // or use it as is
}

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