2016-11-28 118 views
0

如何讓asp.net webapi查看路徑數據和正文以綁定到複雜對象?c#Webapi和模型與fluentvalidation的綁定

使用以下路線「API /產品/ {產品ID} /廠商/ {manufacturerId}」我需要產品ID和manufacturerId綁定到一個模型,所以我的控制方法是

public IHttpActionResult Create(CreateProductManufacturerModel 
       createProductManufacturerModel) 

和我模型是

public class CreateProductManufacturerModel 
    { 
     public int ProductId { get; set; } 
     public int ManufacturerId { get; set; } 
     public bool IsDefault { get; set; } 
     public string ManufacturerCode { get; set; } 
     public string Description { get; set; } 
    } 

我知道我可以改變我的方法如下是的,但我使用fluentvalidation來驗證整個createproductmanufacturermodel,這是自動完成(見式http://www.justinsaraceno.com/2014/07/fluentvalidation-with-webapi2/)。因此,productId和manufacturerId將不會被正確驗證,因爲它們被設置爲零。

public IHttpActionResult Create(int productId, int manufacturerId, CreateProductManufacturerModel 
       createProductManufacturerModel) 

我已經試過模型綁定器,但它不會自動觸發fluentvalidation。不太確定這是否重要,但發佈的主體是json格式。

在此先感謝。

保羅

+0

爲什麼不能在'createproductmanufacturermodel'中添加productId和manufacturerId以及json數據中的其他值? – user3014311

+0

你可以,但這讓我感覺很髒,因爲數據提供了兩次 – phooey

回答

1
  1. 繼承System.Web.Http.Filters.ActionFilterAttribute
  2. 覆蓋OnActionExecuting()
  3. 使用使用actionContext.ActionArguments
  4. 驗證,並指定將數據路由到模特屬性
  5. 裝飾與您創建的新屬性,你的行動actionContext.RequestContext.RouteData.Values
  6. 提取模型提取路由數據。

如果這是一個較不具體的用例,那麼可以使用反射根據參數名稱將路由數據分配給模型屬性。

+0

謝謝Dev Moviit - 完美的工作 – phooey

0

你可以改變你的行動的簽名是:

public IHttpActionResult Create([FromBody]CreateProductManufacturerModel 
      createProductManufacturerModel){} 

,然後確認你所需要的2個值:createProductManufacturerModel.ProductId和createProductManufacturerModel.ManufacturerId?

+0

我目前正在使用我提到的productId,manufacturerId和createProductManufacturerModel的方法。正如我目前有fluentvalidation自動啓動驗證。我會有兩組驗證:( – phooey