使用C#.net在winform中调用和使用Web API

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

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

KEY:“HelloWorld”

价值:{“email”:“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)Not Found.”

你可以看看

> Calling a Web API From a .NET Client in ASP.NET Web API 2

您需要的第一件事是安装Web API客户端库:
从Tools菜单中,选择Library Package Manager,然后选择Package Manager Console.在“程序包管理器控制台”窗口中,键入以下命令:

Install-Package Microsoft.AspNet.WebApi.Client

然后发送这样的帖子请求

// HTTP POST
var gizmo = new Product() { Name = "Gizmo", Price = 100, Category = "Widget" };
response = await client.PostAsJsonAsync("api/products", gizmo);
if (response.IsSuccessStatusCode)
{
    // Get the URI of the created resource.
    Uri gizmoUrl = response.Headers.Location;
}
https://stackoverflow.com/questions/32716174/call-and-consume-web-api-in-winform-using-c-net

转载注明原文:使用C#.net在winform中调用和使用Web API