【问题标题】:Dynamic property name in API inputAPI 输入中的动态属性名称
【发布时间】:2017-07-31 17:47:20
【问题描述】:

我有一个 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)

使用布拉德利的建议,我似乎可以通过自定义模型绑定来做到这一点。但是,我必须设置每个模型属性,而不仅仅是我想设置的一个 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;

    }

【问题讨论】:

  • 您可以使用ActionFilter 来定位参数并在调用CreateDetEntry 之前更改其名称。
  • 实际上,custom ModelBinder 可能更适合更改数据的映射方式。

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


【解决方案1】:

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
}

【讨论】:

  • 如果数据不是以 JSON 表示法传递,这仍然有效吗?我不认为 API 使用 JSON,因为当我在参数中有 [FromBody] 时它不起作用。另外,接受所有参数是最佳做法吗?我喜欢对其进行强烈验证
猜你喜欢
  • 2011-07-12
  • 2015-07-27
  • 1970-01-01
  • 2012-08-21
  • 1970-01-01
  • 2018-07-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多