2016-11-28 54 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