【问题标题】:Call and consume Web API in winform using C#.net使用 C#.net 在 winform 中调用和使用 Web API
【发布时间】:2015-12-19 09:21:35
【问题描述】:

我是初学者,正在创建 winform 应用程序。在其中我必须使用 API 进行简单的 CRUD 操作。我的客户与我共享 API 并要求以 JSON 的形式发送数据。

API:http://blabla.com/blabla/api/login-valida

键:“HelloWorld”

值:{“电子邮件”:“user@gmail.com”,“密码”:“123456”,“时间”:“2015-09-22 10:15:20”}

响应:Login_id

如何将数据转换为 JSON,使用 POST 方法调用 API 并获得响应?

编辑 我在stackoverflow上的某个地方找到了这个解决方案

public static void POST(string url, string jsonContent)
{
    url="blabla.com/api/blala" + url;
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(baseURL);
    request.Method = "POST";

    System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
    Byte[] byteArray = encoding.GetBytes(jsonContent);

    request.ContentLength = byteArray.Length;
    request.ContentType = @"application/json";

    using (Stream dataStream = request.GetRequestStream())
    {
        dataStream.Write(byteArray, 0, byteArray.Length);
    }
    long length = 0;
    try
    {
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            length = response.ContentLength;
            
        }
    }
    catch
    {
        throw;
    }
}
//on my login button click 
private void btnLogin_Click(object sender, EventArgs e)
{
    CallAPI.POST("login-validate", "{ \"email\":" + txtUserName.Text + " ,\"password\":" + txtPassword.Text + ",\"time\": " + DateTime.Now.ToString("yyyy-MM-dd h:mm tt") + "}");
}

我收到异常提示“远程服务器返回错误:(404) 未找到。”

【问题讨论】:

    标签: c# asp.net .net winforms asp.net-web-api


    【解决方案1】:

    您可以查看以下文档教程:

    但作为答案,我将在这里分享一个快速简短的分步指南,介绍如何在 Windows 表单中调用和使用 Web API:

    1. 安装包 - 安装Microsoft.AspNet.WebApi.Client NuGet 包(Web API 客户端库)。

      打开工具菜单 → NuGet 包管理器 → 包管理器控制台 → 在包管理器控制台窗口中,键入以下命令:

       Install-Package Microsoft.AspNet.WebApi.Client
      

      您也可以通过右键单击项目并选择管理 NuGet 包来安装包。

    2. 设置 HttpClient - 创建HttpClient 的实例并设置其BaseAddressDefaultRequestHeaders。例如:

       // In the class
       static HttpClient client = new HttpClient();
      
       // Put the following code where you want to initialize the class
       // It can be the static constructor or a one-time initializer
       client.BaseAddress = new Uri("http://localhost:4354/api/");
       client.DefaultRequestHeaders.Accept.Clear();
       client.DefaultRequestHeaders.Accept.Add(
           new MediaTypeWithQualityHeaderValue("application/json"));
      
    3. 发送请求 - 要发送请求,您可以使用HttpClient 的以下方法:

      • 获取:GetAsyncGetStringAsyncGetByteArrayAsyncGetStreamAsync
      • 发布:PostAsyncPostAsJsonAsyncPostAsXmlAsync
      • 输入:PutAsyncPutAsJsonAsyncPutAsXmlAsync
      • 删除:DeleteAsync
      • 另一种HTTP方法:Send

      注意:要为方法设置请求的URL,请记住,由于您在定义client时已经指定了基本URL,那么这里对于这些方法,只需通过路径、路由值和查询字符串,例如:

       // Assuming http://localhost:4354/api/ as BaseAddress 
       var response = await client.GetAsync("products");
      

       // Assuming http://localhost:4354/api/ as BaseAddress 
       var product = new Product() { Name = "P1", Price = 100, Category = "C1" };
       var response = await client.PostAsJsonAsync("products", product);
      
    4. 获取响应

      要获得响应,如果您使用了GetStringAsync 之类的方法,那么您将响应作为字符串,并且足以解析响应。如果响应是一个你知道的 Json 内容,你可以很容易地使用 Newtonsoft.Json 包的 JsonConvert 类来解析它。例如:

       // Assuming http://localhost:4354/api/ as BaseAddress 
       var response = await client.GetStringAsync("product");
       var data = JsonConvert.DeserializeObject<List<Product>>(response);
       this.productBindingSource.DataSource = data; 
      

      如果您使用过GetAsyncPostAsJsonAsync 之类的方法,并且您有HttpResponseMessage,那么您可以使用ReadAsAsyncReadAsByteArrayAsyncReadAsStreamAsync、`ReadAsStringAsync,例如:

       // Assuming http://localhost:4354/api/ as BaseAddress 
       var response = await client.GetAsync("products");
       var data = await response.Content.ReadAsAsync<IEnumerable<Product>>();
       this.productBindingSource.DataSource = data;
      

    性能提示

    • HttpClient 是一种旨在创建一次然后共享的类型。所以不要试图在每次你想使用它的时候把它放在一个 using 块中。相反,创建类的实例并通过静态成员共享它。要了解更多信息,请查看Improper Instantiation antipattern

    设计提示

    • 尽量避免将 Web API 相关代码与您的应用程序逻辑混在一起。例如,假设您有一个产品 Web API 服务。然后要使用它,首先定义一个IProductServieClient 接口,然后作为实现将所有WEB API 逻辑放入您实现的ProductWebAPIClientService 中,以包含与WEB API 交互的代码。你的应用程序应该依赖IProductServieClient。 (SOLID 原则,依赖倒置)。

    【讨论】:

    • 漂亮的答案。
    【解决方案2】:

    只需使用以下库。

    https://www.nuget.org/packages/RestSharp

    GitHub 项目:https://github.com/restsharp/RestSharp

    示例代码::

        public Customer GetCustomerDetailsByCustomerId(int id)
        {
            var client = new RestClient("http://localhost:3000/Api/GetCustomerDetailsByCustomerId/" + id);
            var request = new RestRequest(Method.GET);
            request.AddHeader("X-Token-Key", "dsds-sdsdsds-swrwerfd-dfdfd");
            IRestResponse response = client.Execute(request);
            var content = response.Content; // raw content as string
            dynamic json = JsonConvert.DeserializeObject(content);
            JObject customerObjJson = json.CustomerObj;
            var customerObj = customerObjJson.ToObject<Customer>();
            return customerObj;
        }
    

    【讨论】:

    • jsonData 对象的引用在哪里?
    • @Zeeshanef 抱歉,出了点问题。编辑成功。现在它应该不会抛出任何编译器错误。
    【解决方案3】:

    【讨论】:

      【解决方案4】:

      使用此代码:

      var client = new HttpClient();
      client.BaseAddress = new Uri("http://www.mywebsite.com");
      var request = new HttpRequestMessage(HttpMethod.Post, "/path/to/post/to");
       
      var keyValues = new List<KeyValuePair<string, string>>();
      keyValues.Add(new KeyValuePair<string, string>("site", "http://www.google.com"));
      keyValues.Add(new KeyValuePair<string, string>("content", "This is some content"));
       
      request.Content = new FormUrlEncodedContent(keyValues);
      var response = await client.SendAsync(request);
      

      【讨论】:

        猜你喜欢
        • 2014-04-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-08
        • 2023-04-01
        • 2019-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多