我一直致力于让 RESTful WCF 服务既接受 JSON 作为参数又返回一些 JSON。
这是我的服务:
[OperationContract] [WebInvoke( Method="POST", BodyStyle = WebMessageBodyStyle.WrappedRequest, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, UriTemplate = "Authenticate")] public AuthResponse Authenticate(AuthRequest data) { AuthResponse res = new AuthResponse(); if (data != null) { Debug.WriteLine(data.TokenId); res.TokenId = new Guid(data.TokenId); } return res; }
以上将设置数据当我通过 { AuthRequest: { TokenId = "some guid"} } 时为 null。
如果我将方法的 BodyStyle 设置为 Bare 那么 数据设置正确,但我必须从 JSON 中删除 { AuthRequest } (我真的不想这样做)。有什么方法可以让 WrappedRequests 使用 { AuthRequest: { TokenId = "some guid"} 作为 JSON?
谢谢。
最佳答案
包装器的名称不是参数类型,而是参数名称。如果您将其发送为 {"data":{"TokenId":"some guid"}}
它应该工作。
或者,如果您想使用参数名称以外的其他名称,可以使用 [MessageParameter]
属性:
[OperationContract]
[WebInvoke(
Method="POST",
BodyStyle = WebMessageBodyStyle.WrappedRequest,
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "Authenticate")]
public AuthResponse Authenticate([MessageParameter(Name = "AuthRequest")] AuthRequest data)
关于WCF BodyStyle WrappedRequest 不适用于传入的 JSON 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7275169/