我有一個ASP.NET核心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'之前改變它的名字。 –
實際上,[定製'ModelBinder'](http://blog.learningtree.com/creating-a-custom-web-api-model-binder/)可能更適合於改變數據映射的方式。 –