RESTful WCF json 请求和 json 响应返回 null

发布于 10-08 20:32 字数 2561 浏览 5 评论 0原文

我正在尝试为 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;
    }

}

I am trying to build a sample for RESTful WCF. The request and response is JSON. The response that I get is:

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

I need to get proper response.

Here is the code:

Web.config has configuration for Restful:

service contract:

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

Implementation:

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;
}

Client:

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;
    }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

相思故2024-10-15 20:32:06
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)
}
public static string SendRequest(string uri, string method, string contentType, string body) {...}

somehow it works only fine for "GET" methods.

For POST methods, I had to call the service operations in different manner on the client side:

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)
}
暮色兮凉城2024-10-15 20:32:06

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

I believe the DataContract object needs to have a parameterless constructor for the serializer to work correctly. I.e. public Person() { }, also you may need to add getters and setters for your public members, public string FirstName{ get; set; }.

寒江雪…2024-10-15 20:32:06

问题:

的空 JSON 响应

获取 { } 在此处输入图像描述

界面:

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

Web 方法:

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

解决方案:

检查类属性是否为公共。

Problem:

Getting an empty JSON response of { }

enter image description here

The Interface:

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

The web method:

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

In the class, I had turned the fields to internal and private!!!

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

Solution:

Check class properties are Public.

水溶2024-10-15 20:32:06

1.restful wcf不需要方法名。
2.Json反序列化器不需要参数名称,它将其视为属性名称。
因此,请使用 {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}" 而不是
{""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}

1.Method name is not required for the restful wcf.
2.Json deserializer does not require parameter name, it treat it as property name.
So use {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}" instead of
{""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文