我想知道如何从WCF Restful服务获取返回值,这是POST方法。如果是GET方法,我可以获得返回值。在GET方法中,webClient.DownloadString(url);正在返回结果。但是在POST方法的情况下,webClient.UploadString(url,“POST”,data);没有返回结果,它只是调用Web服务。
我见过很多样本,人们只是用UploadString()方法调用WCF服务post方法,并假设它返回成功。但我想检查返回值并根据该节目显示相应的消息。
//----------------------------------- WCF RESTful service -----------------------------------
[ServiceContract]
public interface IAppService
{
[OperationContract]
[WebInvoke(UriTemplate = "ValidateVisitPIN", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
bool ValidateVisitPIN(VisitPinRequest visitPinRequest);
}
public class AppService : IAppService
{
public bool ValidateVisitPIN(VisitPinRequest visitPinRequest)
{
//......
if(visitPinRequest.visitPin == 100)
return true;
else
return false;
}
}
//----------------------------------- WCF client application -----------------------------------
//POST method
using (WebClient webClient = new WebClient())
{
VisitPinRequest visitPinRequest = new VisitPinRequest();
visitPinRequest.VisitPin = txtVisitPIN.Text;
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(VisitPinRequest));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, visitPinRequest);
string url = webServiceURL + "ValidateVisitPIN";
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
var returnString = webClient.UploadString(url, "POST", data);
}
//Get method
using (WebClient webClient = new WebClient())
{
string url = webServiceURL + "ValidateVisitPIN/" + txtVisitPIN.Text;
string outputString = webClient.DownloadString(url);
MessageBox.Show(outputString);
}
答案 0 :(得分:1)
请试试这个:
private static T Call<T>(string url, string body, int timeOut = 20)
{
var contentBytes = Encoding.UTF8.GetBytes(body);
var request = (HttpWebRequest)WebRequest.Create(url);
request.Timeout = timeOut * 1000;
request.ContentLength = contentBytes.Length;
request.Method = "POST";
request.Accept = "application/json";
using (var requestWritter = request.GetRequestStream())
requestWritter.Write(contentBytes, 0, (int)request.ContentLength);
var responseString = string.Empty;
var webResponse = (HttpWebResponse)request.GetResponse();
var responseStream = webResponse.GetResponseStream();
using (var reader = new StreamReader(responseStream))
{
reader.BaseStream.ReadTimeout = timeOut * 1000;
responseString = reader.ReadToEnd();
}
return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(responseString);
}
然后你可以这样称呼它:
var input = new
{
test1="",
.
.
.
}
var output = Call<bool>(url, Newtonsoft.Json.JsonConvert.SerializeObject(input));