我创建了一个像下面这样的宁静的网络服务
操作合同
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped,ResponseFormat = WebMessageFormat.Json, UriTemplate = "/PushNotification")]
[OperationContract]
void PushNotification(MailInformation mailInformations);
MailInformations类
[DataContract]
public class MailInformation
{
[DataMember]
public List<string> To { get; set; }
[DataMember]
public string SenderEmail { get; set; }
[DataMember]
public string Subject { get; set; }
}
如何使用HttpWebrequest调用此服务?
我的服务网址
本地主机/聊天/ ChatService.svc / PushNotification
答案 0 :(得分:4)
MailInformation mi = new MailInformation(){
SenderEmail = "aaa@bbb.com",
Subject = "test",
To = new List<string>(){"ccc@eee.com"}
};
var dataToSend = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(mi));
var req = HttpWebRequest.Create("http://localhost/Chat/ChatService.svc/PushNotification");
req.ContentType = "application/json";
req.ContentLength = dataToSend.Length;
req.Method = "POST";
req.GetRequestStream().Write(dataToSend,0,dataToSend.Length);
var response = req.GetResponse();
答案 1 :(得分:0)
您可以省去使用HttpWebRequest
的麻烦,只需使用RestSharp。
var client = new RestClient("http://localhost");
var request = new RestRequest("Chat/ChatService.svc/PushNotification");
RestResponse response = client.Execute(request);
var content = response.Content; // raw content as string