Best practice for passing enum params in Web API

前端 未结 4 1639
迷失自我
迷失自我 2021-01-07 16:30

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

Scenario 1 : Straightforward Enum Param

相关标签:
4条回答
  • 2021-01-07 17:07

    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.
    }
    
    0 讨论(0)
  • 2021-01-07 17:10

    The simplest answer is, "It doesn't matter".

    If the parameter in your controller method is of the enumeration type

    public IHttpActionResult Foo(RuleType ruleType)
    

    In WebAPI, It Just Works - no matter if the client request URL specifies the parmeter value as ?ruleType=1 or ?ruleType=EmailAddress

    If the client specifies a value that isn't valid for the enumeration, an exception is thrown (The parameters dictionary contains a null entry for parameter 'ruleType' of non-nullable type 'RuleType' for method 'Foo' ... and the client gets a 400 Bad Request response.

    0 讨论(0)
  • 2021-01-07 17:16

    For scenario 2 there is built in support in C# for Bitmask operations in Enums using the [Flags] attribute

    [Flags]
    public enum OptionalField
    {
        None = 0,
        RuleOwner = 1,
        Rule = 2,
        RuleAdministrator = 4,
        RuleEditor = 8,
        ...etc
    }
    

    Which is described in this SO post

    As Christian already stated in his answer it's probably not good practice to use this in a REST API but it should work.

    0 讨论(0)
  • 2021-01-07 17:16

    Multiple values or not, if you are using an Enum as a string, you have to parse it manually. In .NET the Enums are integers so if you want to send an enum to the default model binder you have to do it like this: ?ruleType=1.

    You can write your own model binder that will accept string, but you have to ask yourself why are we doing it? If you want the user to be able to easily identify the url then use strings. If not there is no reason not to use integers. As you said, you can use FlagsAttribute to combine multiple values.

    0 讨论(0)
提交回复
热议问题