带有枚举输入参数的 Webapi post 方法

Bos*_*oss 5 c# asp.net-web-api2

尝试调用将枚举作为输入参数的 Web API 方法时,为什么会出现以下屏幕截图中的错误?我该如何解决?

messageDestinationType无论我做什么,它似乎始终为空...

我更愿意将输入类型保留为枚举。我刚开始使用 web api,无法理解当 WCF 完美地处理这种情况时,这有多么困难

[JsonConverter(typeof(StringEnumConverter))]    
public enum MessageDestinationType
{
    None = 0,
    [EnumMember(Value = "SMS")]
    SMS = 1,
    [EnumMember(Value = "Email")]
    Email = 2,
    PushNotification = 3,
    UXP = 4,
    IntermediaryApp = 5,
    YouthApp = 6
}



    [HttpPost, Route("ReadClientMessagesC")]
    public IHttpActionResult ReadClientMessagesC([FromBody]MessageDestinationType messageDestinationType)
    {
        var request = new ClientInboxRequest
        {
            Gcn = Gcn,
            ClientIpAddress = ClientIpAddress,
            CallingApplication = CallingApplication.Name,
            CallingApplicationVersion = CallingApplication.Version,
            CookieString = CookieString,
            HasPbUk = HasPbUk,
            HasIamIms = HasIamIms,
            HasPbZa = HasPbZa,
            HasSps = HasSps,
            HasWiUk = HasWiUk,
            HasWiZa = HasWiZa,
            LinkedGcns = LinkedGcns,
            RequestId = RequestId.ToString(),
            SsoProfiles = SsoProfiles.Select(x => x.Name).ToList()
        };

        MessageDestinationType messageDestination = (MessageDestinationType)messageDestinationType;

        return Ok(ClientMessageCenterHelper.ReadClientMessagesA(Gcn, messageDestination, request));
    }
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

错误消息:{ "Message": "请求无效。", "MessageDetail": "参数字典包含一个 null 条目,用于方法 'API.Domain.ClientMessageCenter.MessageDestinationType' 的不可为空类型的参数 'messageDestinationType' System.Web.Http.IHttpActionResult ReadClientMessagesC(API.Domain.ClientMessageCenter.MessageDestinationType)' in 'ID.ClientMessageCenter.Controllers.ClientMessageCenterController'。可选参数必须是引用类型、可为空类型或声明为可选参数。 ” }

小智 -1

您有几种不同的选择来解决这个问题:

  • 如果您可以更改发送到 的数据ReadClientMessagesC,请将数据作为intEnum值)而不是Enum描述传递。
  • 如果无法更改传入数据,请将参数类型更改为并在方法体中string使用Enum.Parse或;
  • 保留所编写的方法并使用自定义模型绑定器将.stringMessageDestinationType