【问题标题】:ASP.NET Web API binding model properties to different request propertiesASP.NET Web API 将模型属性绑定到不同的请求属性
【发布时间】:2013-03-11 17:44:42
【问题描述】:

我正在尝试编写一个自定义模型绑定器,它可以将用属性装饰的属性绑定到不同名称的请求属性,例如

JSON 请求

{
    "app": "acme"
}

请求模型(摘录)

[Alias("app")]
public string ApplicationName { get; set; }

... 应该导致ApplicationName 被填充值“acme”。我在为此编写自定义模型绑定器时遇到困难:

模型绑定

public BindToAliasModelBinder : IModelBinder {
    public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext) {
        ...
    }
}

模型绑定器提供者

public class BindFromAliasModelBinderProvider : ModelBinderProvider {
    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType) {
        return new BindFromAliasModelBinder();
    }
}

我已在全球范围内注册了提供程序,并且按预期命中了活页夹。我不知道下一步该做什么 - 如何遍历请求值并根据属性的存在有条件地绑定?

【问题讨论】:

    标签: asp.net-web-api


    【解决方案1】:

    如果您只想使用别名,您可以在属性上使用JsonPropertyAttribute,例如[JsonProperty(PropertyName = "app")]

    【讨论】:

    • 我试过这个,不幸的是它似乎不适用于绑定。我也没有运气的DataMember 属性。
    • 你有没有找到解决办法。我不想在实际的 json 中使用短名称,但使用有意义的变量名进行调试
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 2014-02-03
    • 1970-01-01
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多