【发布时间】: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