为POST Web API使用可选的复杂类型操作参数

时间:2015-05-25 10:11:02

标签: asp.net asp.net-web-api http-post restful-architecture

我正在尝试使用以下原型编写API:

[HttpPost]
public ApplicationStatus appLogIn(string id, UserCredentials userCredentials = null)

但是当我向此API发出请求时,无论是否有userCredentials,我都会收到以下错误,其响应代码为500

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "Optional parameter 'userCredentials' is not supported by 'FormatterParameterBinding'.",
  "ExceptionType": "System.InvalidOperationException",
  "StackTrace": null
}

如果我没有将userCredentials设为可选,那么一切正常。 userCredential定义如下:

public class UserCredentials
{
    public string password { get; set; }
    public string username { get; set; }
}

1 个答案:

答案 0 :(得分:5)

尝试将API定义更改为:

[HttpPost]
public ApplicationStatus appLogIn(string id, UserCredentials userCredentials)

由于UserCredentials是引用类型,如果客户端未提供值,则将其设置为null