【问题标题】:Case-insensitive enum in ASP .NET Web APIASP .NET Web API 中不区分大小写的枚举
【发布时间】: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


【解决方案1】:

事实证明,在我的例子中,在对象被传递给控制器​​之前,有一个自定义转换器用于对象。该转换器使用Enum.TryParse 解析值:

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

我把它改成了

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

这使得解析不区分大小写。

请注意,这是一个不属于 ASP.NET 本身的自定义转换器。当我完全删除该转换器并且仅使用本机功能时,该问题并未发生。

【讨论】:

    猜你喜欢
    • 2023-01-18
    • 2015-10-27
    • 1970-01-01
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 2012-02-22
    • 2016-01-20
    • 1970-01-01
    相关资源
    最近更新 更多