JSON 的 WCF REST POST:参数为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6835872/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 17:56:37  来源:igfitidea点击:

WCF REST POST of JSON: Parameter is empty

wcfjsonfiddler

提问by Ian Vink

Using Fiddler I post a JSON message to my WCF service. The service uses System.ServiceModel.Activation.WebServiceHostFactory

我使用 Fiddler 将 JSON 消息发布到我的 WCF 服务。该服务使用 System.ServiceModel.Activation.WebServiceHostFactory

[OperationContract]
[WebInvoke
(UriTemplate = "/authenticate",
       Method = "POST",
       ResponseFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.WrappedRequest
       )]
String Authorise(String usernamePasswordJson);

When the POST is made, I am able to break into the code, but the parameter usernamePasswordJsonis null. Why is this?

进行 POST 后,我可以破解代码,但参数usernamePasswordJsonnull。为什么是这样?

Note: Strangly when I set the BodyStyleto Bare, the post doesn't even get to the code for me to debug.

注意:奇怪的是,当我将BodyStyle设置为Bare 时,该帖子甚至没有提供给我调试的代码。

Here's the Fiddler Screen: enter image description here

这是 Fiddler 屏幕: 在此处输入图片说明

回答by carlosfigueira

You declared your parameter as type String, so it is expecting a JSON string - and you're passing a JSON object to it.

您将参数声明为 String 类型,因此它需要一个 JSON 字符串 - 并且您将一个 JSON 对象传递给它。

To receive that request, you need to have a contract similar to the one below:

要接收该请求,您需要签订与以下类似的合同:

[ServiceContract]
public interface IMyInterface
{
    [OperationContract]
    [WebInvoke(UriTemplate = "/authenticate",
           Method = "POST",
           ResponseFormat = WebMessageFormat.Json,
           BodyStyle = WebMessageBodyStyle.Bare)]
    String Authorise(UserNamePassword usernamePassword);
}

[DataContract]
public class UserNamePassword
{
    [DataMember]
    public string UserName { get; set; }
    [DataMember]
    public string Password { get; set; }
}