在Web API中传递枚举参数的最佳实践 [英] Best practice for passing enum params in Web API

查看:502
本文介绍了在Web API中传递枚举参数的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个RESTful Web API项目,并且我不确定2种不同的Enum方案,我不确定最好的做法。

I have a RESTful Web API project, and I have 2 different Enum scenarios that I'm unsure of re best practice.

方案1:简单明了枚举参数

我的API方法需要一个名为 ruleType 的参数,有效值为 EmailAddress IPAddress
我在Web API项目中的枚举如下:

My API method requires a parameter called ruleType, with valid values being EmailAddress and IPAddress. My enum within the Web API project looks like this:

public enum RuleType
{
    None = 0,
    EmailAddress = 1,
    IPAddress = 2
}

对于这种情况,我的问题是,我是否应该在对API的请求中使用?ruleType = EmailAddress (该值会自动将该值绑定到我的 RuleType 属性)?如果是这样,如何最好地验证发送的 RuleType 参数是有效的RuleType枚举值?

My question for this scenario is, should I use ?ruleType=EmailAddress in my request to the API (which automatically binds that value to my RuleType property within the API method)? If so, how best to validate that the RuleType param sent, is a valid RuleType Enum value?

方案2:单个参数有多个枚举值

我的API方法具有可选的字段参数,它使您可以指定应返回的任何其他数据。例如。 & fields = ruleOwner,rule 。这将在响应中返回这两个额外的数据。

My API method has an optional fields param, which is allows you to specify any additional data that should be returned. E.g. &fields=ruleOwner,rule. This would return those 2 extra bits of data in the response.

我在Web API项目中有一个枚举,该枚举与每个可能的字段,目前,我将逗号分隔的字段参数拆分,然后遍历该枚举的每个字符串表示形式,将其解析为等效的枚举,从而得到一个Enum值列表,然后可以在我的API中使用它来检索相关数据。

I have an enum in the Web API project which relates to each possible field that may be requested, and at present, I am splitting the comma separated fields param, then looping through each string representation of that enum, parsing it to the equivalent enum, resulting in a list of Enum values which I can then use within my API to retrieve the relevant data.

这是枚举:

public enum OptionalField
{
    None = 0,
    RuleOwner = 1,
    Rule = 2,
    etc.
}

这里的最佳做法是什么?我正在研究按位枚举,因此在API请求中发送了一个值,该值导致字段的任意组合,但不知道这是否适合Web API,或者通常是否有更好的方法来解决此问题?

What would be best practice here? I was looking into bitwise enums, so a single value is sent in the API request which resulted in any combination of fields but didn't know if this would work well with a Web API, or if there's generally a better way to go about this?

推荐答案

最佳做法是使URI成为人类可读。这样我也可以理解为什么您使用Enum作为字符串。但是正如HristoKolev所说,您必须编写一个自定义的Model Binder。

it is a best practice to make the URI "human readable". so i can also understand why you using Enum as a string. But as HristoKolev said you have to write a custom Model Binder.

在字段中,我认为您不应该使用枚举的组合。因为很难理解。也许您可以创建作为枚举条目的枚举组合

In fields i think you should not use an combination of enums. because it is difficult to understand. perhaps you can create an combination of enum as enum entry

public enum OptionalField
{
    None = 0,
    RuleOwner = 1,
    Rule = 2,
    RuleAndRuleOwner = 3,
    etc.
}

这篇关于在Web API中传递枚举参数的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆