Я пытаюсь создать пример для 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;
}
}