使用 C#.net 在 winform 中调用和使用 Web API [英] Call and consume Web API in winform using C#.net

查看:45
本文介绍了使用 C#.net 在 winform 中调用和使用 Web API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am beginner and creating winform application. In which i have to use API for Simple CRUD operation. My client had shared API with me and asked to send data in form of JSON.

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

键:HelloWorld"

KEY : "HelloWorld"

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

Value : { "email": "user@gmail.com","password": "123456","time": "2015-09-22 10:15:20"}

响应:Login_id

Response : Login_id

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

How can i convert data to JSON, call API using POST method and get response?

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

EDIT Somewhere on stackoverflow i found this solution

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) 未找到."

I got exception that says "The remote server returned an error: (404) Not Found."

推荐答案

你可以看看下面的文档教程:

You can take a look at the following docs tutorial:

但作为答案,我将在这里分享一个关于如何在 Windows 窗体中调用和使用 Web API 的快速而简短的分步指南:

But as an answer, here I will share a quick and short a step by step guide about how to call and consume web API in Windows forms:

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

  1. Install Package - Install the Microsoft.AspNet.WebApi.Client NuGet package (Web API Client Libraries).

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

Open Tools menu → NuGet Package Manager → Package Manager Console → In the Package Manager Console window, type the following command:

 Install-Package Microsoft.AspNet.WebApi.Client

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

You can install package by right click on project and choosing Manage NuGet Packages as well.

设置 HttpClient - 创建 HttpClient 并设置其BaseAddressDefaultRequestHeaders.例如:

Set up HttpClient - Create an instance of HttpClient and set up its BaseAddress and DefaultRequestHeaders. For example:

 // 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"));

  • 发送请求 - 要发送请求,您可以使用 HttpClient:

  • Send Request - To send the requests, you can use the following methods of the HttpClient:

    • GET:GetAsyncGetStringAsyncGetByteArrayAsyncGetStreamAsync
    • POST:PostAsyncPostAsJsonAsyncPostAsXmlAsync
    • PUT:PutAsyncPutAsJsonAsyncPutAsXmlAsync
    • 删除:DeleteAsync
    • 另一种 HTTP 方法:Send
    • GET: GetAsync, GetStringAsync, GetByteArrayAsync, GetStreamAsync
    • POST: PostAsync, PostAsJsonAsync, PostAsXmlAsync
    • PUT: PutAsync, PutAsJsonAsync, PutAsXmlAsync
    • DELETE: DeleteAsync
    • Another HTTP method: Send

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

    Note: To set the URL of the request for the methods, keep in mind, since you have specified the base URL when you defined the client, then here for these methods, just pass path, route values and query strings, for example:

     // 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);
    

  • 获取回复

    要获取响应,如果您使用了诸如 GetStringAsync 之类的方法,那么您将响应作为字符串,并且足以解析响应.如果响应是您知道的 Json 内容,您可以轻松使用 JsonConvertNewtonsoft.Json 包来解析它.例如:

    To get the response, if you have used methods like GetStringAsync, then you have the response as string and it's enough to parse the response. If the response is a Json content which you know, you can easily use JsonConvert class of Newtonsoft.Json package to parse it. For example:

     // 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,例如:

    If you have used methods like GetAsync or PostAsJsonAsync and you have an HttpResponseMessage then you can use ReadAsAsync, ReadAsByteArrayAsync, ReadAsStreamAsync, `ReadAsStringAsync, for example:

     // 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 块中.相反,创建类的实例并通过静态成员共享它.要了解更多相关信息,请查看 不正确的实例化反模式

    设计提示

    • 尽量避免将 Web API 相关代码与您的应用程序逻辑混在一起.例如,假设您有一个产品 Web API 服务.然后使用它,首先定义一个 IProductServieClient 接口,然后作为一个实现,将所有的 WEB API 逻辑放在 ProductWebAPIClientService 中,你实现它来包含与 WEB API 交互的代码.您的应用程序应该依赖于 IProductServieClient.(SOLID 原则,依赖倒置).
    • Try to avoid mixing the Web API related code with your application logic. For example let's say you have a product Web API service. Then to use it, first define an IProductServieClient interface, then as an implementation put all the WEB API logic inside the ProductWebAPIClientService which you implement to contain codes to interact with WEB API. Your application should rely on IProductServieClient. (SOLID Principles, Dependency Inversion).

    这篇关于使用 C#.net 在 winform 中调用和使用 Web API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆