jquery - 如何使用 Jquery/WebClient/WebRequest 并以多个类对象作为参数来使用 WCF Rest

标签 jquery wcf rest webclient

我的目标是使用两种方式使用 WCF Rest

  1. 使用 Jquery
  2. 使用 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)
  1. 应用程序 objApplication
  2. 电子邮件(作为字符串参数)
  3. 选项 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;}      
     }
    

如何从网络客户端发送这些参数并获得响应。

我们还需要从 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);

Web请求代码:

    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”

附加数据契约(Contract):

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())

关于jquery - 如何使用 Jquery/WebClient/WebRequest 并以多个类对象作为参数来使用 WCF Rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23235473/

相关文章:

javascript - Angular JS : rest API is called with a delay

node.js - 我可以使用 XML 创建 REST API 作为响应吗?

javascript - 在 Javascript 或 jQuery 中获取颜色深浅?

c# - MassTransit 实现 : sometimes message not received

c# - 可序列化与数据契约与 WCF 服务中什么都没有

asp.net - Web 应用程序需要 WCF 吗?

jquery文件上传插件: how to use callbacks?

javascript - 样式单选按钮,只显示选中

javascript - 在 Kendo Treeview 中将箭头符号设为加号(+)和减号(-)

python - 为 Django 应用程序创建 REST API