枚举的Web API模型绑定器

时间:2018-04-11 14:49:00

标签: c# asp.net-web-api asp.net-web-api2 model-binding

我对Web API 2有以下枚举:

[TypeConverter(typeof(StringEnumConverter))]
public enum SortDirection
{
    [EnumMember(Value = "asc")] Ascending,
    [EnumMember(Value = "desc")] Descending
}

我在TypeConverterAttribute使用StringEnumConverter Newtonsoft.Json // "property": "asc" // "property": "desc" 。如果我将此枚举序列化为JSON,它看起来就像我想要的那样:

?direction=desc

我希望能够将此绑定到来自Web API中的URI的模型,以便我可以传入public class ExampleController : ApiController { public IHttpActionResult GetAll([FromUri]SortDirection sortDir) { // the above property is not binding to value asc / dir from the query string // it only binds to 0/1 or Ascending/Descending } }

?direction=0|1

目前,我可以传递?direction=Ascending|DescendingSortDirection,Web API会绑定它。

我希望能够在不明确引用EnumMemberAttribute的情况下执行此操作...我使用的任何枚举[A-Z]\S+ 我想将此逻辑应用于。

我该如何做到这一点?

0 个答案:

没有答案
相关问题