【问题标题】:c# Webapi and model binding with fluentvalidationc# Webapi和模型绑定与fluentvalidation
【发布时间】:2017-04-12 02:52:34
【问题描述】:

如何让 asp.net webapi 查看路由数据和主体以绑定到复杂对象?

使用以下路由“api/products/{productid}/manufacturers/{manufacturerId}”我需要productId和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)

我已经尝试过 modelbinder,但它不会自动触发 fluentvalidation。不太确定这是否重要,但发布的正文是 json 格式。

提前致谢。

保罗

【问题讨论】:

  • 为什么不能在createproductmanufacturermodel中添加productId和manufacturerId以及json数据中的其他值?
  • 你可以,但这让我觉得很脏,因为数据提供了两次

标签: c# asp.net-web-api


【解决方案1】:

您能否将您的操作签名更改为:

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

然后验证您需要的 2 个值:createProductManufacturerModel.ProductId 和 createProductManufacturerModel.ManufacturerId ?

【讨论】:

  • 我目前正在使用我提到的productId、manufacturerId和createProductManufacturerModel的方法。因为我目前有 fluentvalidation 自动触发验证。我会有两组验证:(
【解决方案2】:
  1. 继承System.Web.Http.Filters.ActionFilterAttribute
  2. 覆盖OnActionExecuting()
  3. 使用actionContext.RequestContext.RouteData.Values提取路由数据
  4. 使用actionContext.ActionArguments提取模型
  5. 验证路由数据并将其分配给模型属性
  6. 用您创建的新属性装饰您的操作。

如果这是一个不太具体的用例,您可以使用反射根据参数名称将路由数据分配给模型属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 2013-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-04
    相关资源
    最近更新 更多