簡體   English   中英

RESTful WCF json請求和json響應返回null

[英]RESTful WCF json request and json response returns null

我正在嘗試為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;
    }

}

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

問題:

獲取{}的空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

解:

檢查類的屬性為Public。

1.restful wcf不需要方法名稱。 2.Json解串器不需要參數名稱,它將其視為屬性名稱。 因此,請使用{""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}"代替{""getData"" : {""name"" :{""FirstName"":""John"", ""LastName"":""Doe""}}

我相信DataContract對象需要具有無參數構造函數才能使序列化程序正常工作。 即public Person(){},也可能需要為公共成員添加getter和setter,公共字符串FirstName {get; 組; }。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM