我的目标是使用两种方式消耗WCF休息时间
使用jQuery
使用WebClient / WebRequest
案例1:WebClient / WebRequest
string json = client.DownloadString("http://70.0.111.17/VerifyData");
在这里,VerifyData接受三个对象/参数
[OperationContract]
[WebInvoke(UriTemplate = "VerifyEmail", Method = "POST", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
public ServiceResult VerifyEmail(Application application, string email, Options options)
应用程序objApplication
电子邮件(作为字符串参数)
选项objOptions
public class Application
{
public string ApplicationID { get; set; }
public string Login { get; set; }
public string Password { get; set; }
}
public class Options
{
public bool IsActive {get; set;}
public bool IsRequired {get; set;}
}
如何从webclient发送这些参数并获得响应。
另外,我们需要从Jquery执行相同的操作。
请提供一些方法来完成它。
谢谢
最佳答案
WebClient代码:
const string json = @"{
""application"":
{
""ApplicationID"":""1"",
""Login"":""lgn"",
""Password"":""123""
},
""email"": ""email@email"",
""options"":
{
""IsActive"":""true"",
""IsRequired"":""true""
}
}";
Uri uri= new Uri("http://70.0.111.17/VerifyEmail");
var wc = new WebClient();
wc.Headers["Content-Type"] = "application/json";
var resJson = wc.UploadString(uri, "POST", json);
WebRequest代码:
WebRequest wr = WebRequest.Create(uri);
wr.Method = "POST";
wr.ContentType = "application/json";
wr.ContentLength = json.Length;
var requestStream = wr.GetRequestStream();
byte[] postBytes = Encoding.UTF8.GetBytes(json);
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
// grab te response and print it out to the console along with the status code
var response = (HttpWebResponse)wr.GetResponse();
string result;
using (var rdr = new StreamReader(response.GetResponseStream()))
{
result = rdr.ReadToEnd();
}
编辑1:
HttpClient
先决条件:nuget包“ Microsoft.AspNet.WebApi.Client”
附加数据合同:
public class ApplicationRequest
{
public Application application { get;set; }
public string email { get; set; }
public Options options { get; set; }
}
用法:
var client = new HttpClient {BaseAddress = new Uri("http://70.0.111.17")};
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//option 1, you can just pass an object
var responseString =
client.PostAsJsonAsync("VerifyEmail", new ApplicationRequest { email = "email.asdlkfj" }).Result.Content.ReadAsStringAsync().Result;
//option 2, you can pass plain json string
var req = new HttpRequestMessage(HttpMethod.Post, "VerifyEmail");
req.Content = new StringContent(json, Encoding.UTF8, "application/json");
var response2String = client.SendAsync(req).Result.Content.ReadAsStringAsync().Result;
*您必须添加对http错误重新操作的检查(result.IsSuccessStatusCode或response.EnsureSuccessStatusCode())