2017-07-31 234 views
0

我有一個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; 

    } 
+0

你可能可以使用'ActionFilter'來定位參數並在調用'CreateDetEntry'之前改變它的名字。 –

+1

實際上,[定製'ModelBinder'](http://blog.learningtree.com/creating-a-custom-web-api-model-binder/)可能更適合於改變數據映射的方式。 –

回答

0

DTO params在Web API中特別限制了屬性是動態的時候。我之前通過使用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 
} 
+0

如果數據沒有以JSON表示法傳遞,這仍然可以工作嗎?我不認爲API使用JSON,因爲當我在參數中有[FromBody]'時,它不起作用。另外,接受所有參數是否是最佳做法?我喜歡強烈驗證它 –