【发布时间】:2019-04-15 09:37:59
【问题描述】:
在我的 Web API 中,我有一个对包含 enum 属性的对象进行 CRUD 操作的端点。
// 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();
}
//...
}
当使用以下负载调用端点时,它可以正常工作:
{"Username": "jason", "Platform": "Linux"}
ASP .NET 将枚举值正确解析为Platform.Linux
但是,如果大小写不同,例如:
{"Username": "jason", "Platform": "linux"}
然后 ASP .NET 将不会将其识别为 Platform.Linux,而是静默使用默认值 Platform.Windows。
API 从其他服务获取我无法更改的请求,因此我必须支持两种大小写变体。
我知道我可以使用两个具有不同大小写的等效枚举值,如下所示:
public enum Platform
{
Windows=0, windows=0,
Linux=1, linux=1,
MacOS=2, macos=2
}
但我想知道是否有更好的解决方案?
【问题讨论】:
-
我使用的是 .NET Framework 4.5.2; Microsoft.AspNet.WebApi 包的版本是 5.2.3
标签: c# asp.net-web-api enums asp.net-4.5