【问题标题】:Get the object is null using JSON in WCF Service在 WCF 服务中使用 JSON 获取对象为空
【发布时间】:2018-09-25 00:30:35
【问题描述】:

我有一个 WCF 服务,我创建了一个网站来测试我的服务。但是,该对象在方法中始终为 null。我使用 if 语句检查对象,它为空对象返回 false。有人可以解决我如何解决它。

有我的服务:

 [OperationContract]
    [WebInvoke(Method = "POST",
       ResponseFormat = WebMessageFormat.Xml,
        RequestFormat = WebMessageFormat.Json,
       BodyStyle = WebMessageBodyStyle.WrappedRequest,          
       UriTemplate = "BookInfo/")]

    BookingResult Booking(BookInfo bookInfo);


 public BookingResult Booking(BookInfo bookInfo)
    {
        BookingResult result = new BookingResult();            
        if (bookInfo == null)
        {
            result.isSucceed = false;
        }
        else
        {
            result.isSucceed = true;
        }

        return result;
    }

我的网站上有调用服务的方法。

private string callService(BookInfo input)
    {

        string serviceUrl = "http://localhost:1599026/Booking.svc/BookInfo/";            
        var stringPayload = JsonConvert.SerializeObject(input);   

        WebClient client = new WebClient();
        client.Headers["Content-type"] = "application/json";                    
        client.Encoding = Encoding.UTF8;
        string rtn = client.UploadString(serviceUrl,"POST", stringPayload);
        return rtn;

    }

【问题讨论】:

    标签: c# wcf json.net


    【解决方案1】:

    我做了一个demo,希望对你有用。

    服务器端。

     class Program
    {
        static void Main(string[] args)
        {
            Uri uri = new Uri("http://localhost:2000");
            WebHttpBinding binding = new WebHttpBinding();
            using (ServiceHost sh=new ServiceHost(typeof(MyService),uri))
            {
                ServiceEndpoint se = sh.AddServiceEndpoint(typeof(IService), binding, "");
                se.EndpointBehaviors.Add(new WebHttpBehavior());
    
                Console.WriteLine("service is ready....");
                sh.Open();
    
                Console.ReadLine();
                sh.Close();
            }
        }
    }
    [ServiceContract(ConfigurationName ="isv")]
    public interface IService
    {
        [OperationContract]
        [WebInvoke(Method = "POST",
      ResponseFormat = WebMessageFormat.Xml,
       RequestFormat = WebMessageFormat.Json,
      BodyStyle = WebMessageBodyStyle.WrappedRequest,
            UriTemplate ="BookInfo/")]
        BookingResult Booking(BookInfo bookInfo);
    }
    [ServiceBehavior(ConfigurationName = "sv")]
    public class MyService : IService
    {
    
        public BookingResult Booking(BookInfo bookInfo)
        {
            BookingResult result = new BookingResult();
            if (bookInfo==null)
            {
                result.isSucceed = false;
            }
            else
            {
                result.isSucceed = true;
            }
            return result;
        }
    }
    [DataContract]
    public class BookInfo
    {
        [DataMember]
        public string Name { get; set; }
    }
    [DataContract]
    public class BookingResult
    {
        [DataMember]
        public bool isSucceed { get; set; }
    }
    

    客户端。

    class Program
    {
        static void Main(string[] args)
        {
            string uri = "http://localhost:2000/BookInfo";
            WebClient client = new WebClient();
            client.Headers["Content-type"] = "application/json";
            client.Encoding = Encoding.UTF8;
            BookInfo input = new BookInfo()
            {
                Name = "Apple"
            };
            string str2 = "{\"bookInfo\":" + JsonConvert.SerializeObject(input) + "}";
            string result = client.UploadString(uri, "POST", str2);
            Console.WriteLine(result);
        }
    }
    [DataContract]
    public class BookInfo
    {
        [DataMember]
        public string Name { get; set; }
    }
    

    结果。

    如果我在 Postman 中调用它。

    取决于 BodyStyleResquestFormatResponseFormat 的组合。我们会有不同的格式。

    1:

    ResponseFormat = WebMessageFormat.Json,RequestFormat =
        WebMessageFormat.Json, BodyStyle =
        WebMessageBodyStyle.WrappedRequest,
    

    请求:

    {“bookInfo”:{“name”:”value”}}
    

    回复:

    {“BookingResult”:{“isSucceed”:value}}
    

    2:

    ResponseFormat = WebMessageFormat.Json,RequestFormat =
        WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare,
    

    请求:

    {“name”:”value”}
    

    回复:

    {“isSucceed”:value}
    

    3:

    ResponseFormat = WebMessageFormat.Xml,RequestFormat = WebMessageFormat.Xml,BodyStyle = WebMessageBodyStyle.Bare,
    

    请求:

       <BookInfo xmlns="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            <Name>true</Name>
        </BookInfo>
    

    响应。

    <BookingResult xmlns="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <isSucceed>true</isSucceed>
    </BookingResult>
    

    4:

     ResponseFormat = WebMessageFormat.Xml,RequestFormat WebMessageFormat.Xml,BodyStyle= WebMessageBodyStyle.Wrapped
    

    请求:

    <Booking xmlns="http://tempuri.org/">
        <bookInfo>
        <Name>abcd</Name>
        </bookInfo>
    </Booking>
    

    回复:

    <BookingResponse xmlns="http://tempuri.org/">
    <BookingResult xmlns:a="http://schemas.datacontract.org/2004/07/Server6" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:isSucceed>true</a:isSucceed>
    </BookingResult>
    

    我们还可以使用 MessageParameter 属性手动分配参数的名称。

    [return: MessageParameter(Name ="result")]
    BookingResult Booking([MessageParameter(Name ="book")] BookInfo bookInfo);
    

    请求:

    {“book”:{“Name”:”value”}}
    

    回复:

    {“result”:{“isSucceed”:value}}
    

    如果您有任何问题,请随时与我联系。

    【讨论】:

    • 感谢您的详细回答。我的测试应用是网站。我调试检查 var stringPayload = JsonConvert.SerializeObject(input); 上的代码文本是这样的 "{\"ID\:"2342,\"requestedBy\":\"tester\"}" 如果我​​使用 BodyStyle = WebMessageBodyStyle.Bare,我得到远程服务器返回错误:(400 ) 错误的请求。任何解决它的建议。
    • 我还修改了类似 var stringPayload = "{\"BookInfo\":" + JsonConvert.SerializeObject(input) +"}" 并使用 WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Xml,RequestFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.WrappedRequest,。我还是得到了空对象
    • 注意参数的大小写,要和你的参数一致。这里应该是“bookInfo”。
    • @user819774 你的端口号是1599026?
    • 如果我将代码更改为 "{\"bookInfo\":" + JsonConvert.SerializeObject(input) +"}" ,我得到 The remote server returned an error: (400) Bad请求。
    猜你喜欢
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2012-02-18
    • 1970-01-01
    相关资源
    最近更新 更多