如何使用Jquery / WebClient / WebRequest以及多个类对象作为参数来使用wcf rest

时间:2014-04-23 05:27:57

标签: jquery wcf rest webclient

我的目标是使用两种方式消耗wcf休息

  1. 使用Jquery
  2. 使用WebClient / WebRequest
  3. 案例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)
    
    1. 应用程序objApplication
    2. 电子邮件(作为字符串参数)
    3. options 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;}      
       }
      
    4. 如何从webclient发送这些参数并获得响应。

      我们也需要从Jquery做同样的事情。

      请提供一些方法来完成它。

      由于

2 个答案:

答案 0 :(得分:2)

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 package&#34; Microsoft.AspNet.WebApi.Client&#34;

附加数据合同:

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错误resopnse检查(result.IsSuccessStatusCode或response.EnsureSuccessStatusCode())

答案 1 :(得分:0)

编辑:

从jquery轻松调用此

var url = "http://70.0.111.17/VerifyData";
$.ajax({
  type: "POST",
  url: url,
  data: {"Application": {"ApplicationID": "0","Login":"00","Password":""}},
  success: success
});

OR

$.post( url, data).done(function(data) {...});

从Webclient使用

string Data = "{'Application': {'ApplicationID': '0','Login':'00','Password':''}}";
var appliation = client.UploadString(url, Data);

虽然JSON对象中的双引号是标准的,但它仍然可以工作或使用转义字符来转义双引号。

要了解有关POST的更多信息: WCF - Post JSON object

以其他方式创建JSON: 您可以使用Json.net来序列化应用程序数据

Application data = new Application {AppliationId = "", Login = "", Password ="" };
string output = JsonConvert.SerializeObject(Data);

您可以从nuget包管理器

获取JSON.NET