代码之家  ›  专栏  ›  技术社区  ›  S-Wing

具有自定义对象输入的wcf方法

  •  0
  • S-Wing  · 技术社区  · 6 年前

    我有一个方法,它接收自定义对象作为输入。

    [OperationContract(Name = "MyMethod")]
    public CustomOutput MyMethod(CustomInput inp){}
    
    [DataContract(Namespace = "")]
        public class CustomInput 
        {
            [DataMember(Name = "x")]
            public string x { get; set; }
        }
    

    我从控制台应用程序调用它:

    [DataContract(Namespace = "")]
    public class CustomInput 
    {
        [DataMember(Name = "x")]
        public string x { get; set; }
    }   
    
    class Program { 
    private const string URL2 = "http://.../MyMethod";
    
        static void Main(string[] args)
        {
            HttpClient client = new HttpClient();
            string str = JsonConvert.SerializeObject(new CustomInput () { x = "pippo" });
            HttpContent content = new StringContent(str, Encoding.UTF8, "application/json");
            HttpResponseMessage response = client.PostAsync(URL2, content).Result;  // Blocking call!
            if (response.IsSuccessStatusCode)
            {
            }
            else
            {
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }
        } 
    }
    

    有了这段代码,我可以在服务器上正确调用mymethod,但custominput始终为空。
    有什么建议吗?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ross Bush    6 年前

    我认为wcf服务想要理解json的方式是使用一个外部包装器。

     var data= new
     {
         inp = new CustomInput({ x = "pippo" })
     };
     string str = JsonConvert.SerializeObject(data);