【问题标题】:RESTful WCF json request and json response returns nullRESTful WCF json 请求和 json 响应返回 null
【发布时间】:2011-05-30 04:03:55
【问题描述】:

我正在尝试为 RESTful WCF 构建示例。请求和响应是 JSON。我得到的回应是:

{"FirstName":null,"LastName":null}

我需要得到适当的回应。

代码如下:

Web.config 有 Restful 的配置:

服务合同:

[OperationContract]
        [WebInvoke(UriTemplate = "Data", 
            ResponseFormat = WebMessageFormat.Json)]
        person getData(person name);

实施:

public person getData(person name)
{
    return new person{ FirstName= name.FirstName, LastName= name.LastName };
}

[DataContract]

public class person 
{

[DataMember]
public string FirstName;

[DataMember]
public string LastName;
}

客户:

class Program
{
static void Main(string[] args)
{
            string baseAddress = "http://localhost/RESTfulService";
 SendRequest(baseAddress + "/Data", "POST", "application/json", @"{""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}");
}

  public static string SendRequest(string uri, string method, string contentType, string body)

    {
        string responseBody = null;

        HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(uri);
        req.Method = method;
        if (!String.IsNullOrEmpty(contentType))
        {
            req.ContentType = contentType;
        }
        if (body != null)
        {
            byte[] bodyBytes = Encoding.UTF8.GetBytes(body);
            req.GetRequestStream().Write(bodyBytes, 0, bodyBytes.Length);
            req.GetRequestStream().Close();
        }

        HttpWebResponse resp;
        try
        {
            resp = (HttpWebResponse)req.GetResponse();
        }
        catch (WebException e)
        {
            resp = (HttpWebResponse)e.Response;
        }
        Console.WriteLine("HTTP/{0} {1} {2}", resp.ProtocolVersion, (int)resp.StatusCode, resp.StatusDescription);
        foreach (string headerName in resp.Headers.AllKeys)
        {
            Console.WriteLine("{0}: {1}", headerName, resp.Headers[headerName]);
        }
        Console.WriteLine();
        Stream respStream = resp.GetResponseStream();
        if (respStream != null)
        {
            responseBody = new StreamReader(respStream).ReadToEnd();
            Console.WriteLine(responseBody);
        }
        else
        {
            Console.WriteLine("HttpWebResponse.GetResponseStream returned null");
        }
        Console.WriteLine();
        Console.WriteLine(" *-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-* ");
        Console.WriteLine();

        return responseBody;
    }

}

【问题讨论】:

  • return new mytype 是什么意思? mytype 是什么?
  • 为正确的代码编辑..这是错字
  • 附带说明:您正在使用包装的消息,即方法名称 (getData) 也是消息的一部分。这真的是一个 RESTful 服务还是只是伪装成 JSON 的 SOAP?如果发现使用裸消息更优雅: ([WebInvoke(UriTemplate = "Data/getData", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]。这也可能是您的问题的一部分,因为我怀疑您的消息不是 WCF 所期望的。
  • 你是对的,我需要将此服务用作 SOAP 和 RESTful。能不能实现,我用bare也试过了,还是不行

标签: c# .net wcf json wcf-rest


【解决方案1】:
public static string SendRequest(string uri, string method, string contentType, string body) {...}

不知何故,它只适用于“GET”方法。

对于 POST 方法,我必须在客户端以不同的方式调用服务操作:

uri = "http://localhost/RestfulService";

EndpointAddress address = new EndpointAddress(uri);
WebHttpBinding binding = new WebHttpBinding();
WebChannelFactory<IRestfulServices> factory = new WebChannelFactory<IRestfulServices>(binding, new Uri(uri));
IRestfulServices channel = factory.CreateChannel(address, new Uri(uri));

channel.getData(new Person{firstName = 'John', LastName = 'Doe'});

[ServiceContract]
public interface IRestfulService
{
    [WebInvoke(BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "Data")]
    object getData(Person name)
}

【讨论】:

    【解决方案2】:

    我相信 DataContract 对象需要有一个无参数的构造函数才能使序列化程序正常工作。 IE。 public Person() { },您可能还需要为您的公共成员添加 getter 和 setter,public string FirstName{ get;放; }。

    【讨论】:

      【解决方案3】:

      问题:

      得到 { }

      的空 JSON 响应

      界面:

      [OperationContract]
      [WebInvoke(Method = "GET", UriTemplate = "Client/{idsHashed}", ResponseFormat = WebMessageFormat.Json)]
      Summary GetClientDataById(string idsHashed);
      

      网络方法:

      public Summary GetClientDataById(string idsHashed)
      {
          Summary clientSum = new Summary().GetClientDataById(clientId);
          return clientSum;
      }
      

      在课堂上,我已将字段设置为内部和私有!!!

      public class Summary
      {
          private string clientName { get; set; }  //<--  wont be rendered out as json because its private
      

      解决方案:

      检查类属性是否公开。

      【讨论】:

        【解决方案4】:

        1.restful wcf不需要方法名。 2.Json反序列化器不需要参数名,它把它当作属性名。 所以使用{""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}" 而不是 {""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}.

        【讨论】:

          猜你喜欢
          • 2017-03-12
          • 2013-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-18
          • 2012-01-09
          • 2020-06-13
          • 1970-01-01
          相关资源
          最近更新 更多