2

In my web API, I have an endpoint for CRUD operations on an object that contains enum Properties.

// User.cs
public class User
{
    public string Username { get; set; }
    public Platform Platform { get; set; }
}

public enum Platform
{
    Windows, Linux, MacOS
}

// UserController.cs
public class UserController : ApiController 
{
    public IHttpActionResult Post(User value)
    {
        users.Add(value);
        return Ok();
    }
    //...
}

When the endpoint is called with the following payload, it works fine:

{"Username": "jason", "Platform": "Linux"}

ASP .NET parses the enum value correctly as Platform.Linux However, if the casing is different, e.g:

{"Username": "jason", "Platform": "linux"}

Then ASP .NET will not recognize this as Platform.Linux and will instead silently use the default value Platform.Windows.

The API gets requests from other services that I cannot change, so I have to support both variants of casing.

I know that I can just use two equivalent enum values with different casing like this:

public enum Platform
{
    Windows=0, windows=0,
    Linux=1, linux=1,
    MacOS=2, macos=2
}

But I wonder if there's a better solution?

jfhr
  • 687
  • 5
  • 13
  • I'm on .NET Framework 4.5.2; The Version of the Microsoft.AspNet.WebApi Package is 5.2.3 – jfhr Apr 15 '19 at 10:41

1 Answers1

1

It turns out that in my case, there was a custom converter being used for the object before it was passed to the controller. That converter used Enum.TryParse to parse the value:

if (Enum.TryParse(enumLiteral, out result))
{
    return result;
}

I changed this to

if (Enum.TryParse(enumLiteral, true, out result))
{
    return result;
}

Which made the parsing case-insensitive.

Note that this was a custom converter that is not part of ASP.NET itself. The issue did not occur when I removed that converter entirely and only using native functionality.

jfhr
  • 687
  • 5
  • 13