【问题标题】:Is it possible to set how models are bound in web api 2?是否可以设置模型在 web api 2 中的绑定方式?
【发布时间】:2021-11-23 02:15:07
【问题描述】:

我正在尝试让控制器从发布请求中获取 json 数据并设置我希望它们如何应用于模型。示例:

public string model1 {
    public string name { get; set; }
    public string value { get; set; }
}

public string model2 {
    public string ident { get; set; }
    public IEnumerable<model1> model { get; set; }
}

我希望 model1 包含 json 对象中属性的键、值。例如,{ ident: "moo", model: { fish: "sticks" } } 将生成带有 ident: moo 和 ref model1 的 model2,其中包含一个包含 name:fish 和 value:sticks 的条目。

我可以在控制器中轻松地做到这一点,我想知道是否有一种方法可以通过 web api 2 让我指定我希望如何处理该模型,这样我就不必在每个控制器中复制它模型参考模型1。

谢谢

【问题讨论】:

  • 您可以创建一个custom model binder
  • 我尝试了模型绑定。它似乎仅在模型位于根而不是模型中的模型时才有效。 :(
  • 是的,您需要绑定model2。这里只有一个“模型”而不是两个,那就是model2。 model1 只是模型 2 中包含的一个对象。解决方法还是一样
  • 您为什么使用 Web API 2.0?那是released almost 10 years ago,很快就被后来的版本所取代。更新又快又轻松,有什么问题?
  • @Dai: 只是一个标签。 WebApi2 的命名是为了与 1 区分开来。更高的版本通常仍称为“2”。

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


【解决方案1】:

您可以创建自定义 FilterAttribute 并在 WebAPIConfig.cs 文件中的 Register Method 下全局应用该新自定义过滤器属性

public static void Register(HttpConfiguration config)
{
    config.Filters.Add(new YourCustomFilterAttribute());
    ......
    ......
    ......
}

此自定义过滤器属性将在每次 API 方法调用之前运行。 希望它能达到核心目的。

【讨论】:

    猜你喜欢
    • 2014-01-17
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2013-11-16
    • 2016-05-23
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多