API输入中的动态属性名称

时间:2017-07-31 17:47:21

标签: c# asp.net-mvc api asp.net-core asp.net-apicontroller

我有一个ASP.NET Core API,它接受一个名为DetParameterCreateDto的DTO参数,看起来像这样

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; }
}

我遇到的问题是从客户端传入的参数有一个名为Instrument_Complete的属性;这是动态的。

名称实际为[instrument]_complete,其中[instrument]是工具的名称。因此,如果工具的名称为my_first_project,则参数的属性名称实际为my_first_instrument_complete,这将无法正确映射到我的API的输入参数;所以它总是显示0的值

API方法

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

更新(8/2)

使用bradley的建议似乎我可以通过自定义模型绑定来实现这一点。但是,我必须设置每个模型属性而不是我想要设置的instrument_complete(并从字符串转换一些)。这似乎不是最佳解决方案。

    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;

    }

1 个答案:

答案 0 :(得分:0)

Web API中的

DTO params限制,特别是当属性是动态的时。我之前使用JObject解决了类似的问题。你的可能是这样的:

[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
}