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

Kal*_*dra 9 .net c# json winforms asp.net-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") + "}");
    }
Run Code Online (Sandbox Code Playgroud)

我得到异常,说"远程服务器返回错误:(404)Not Found."

Rez*_*aei 12

你可以看看

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

Install-Package Microsoft.AspNet.WebApi.Client
Run Code Online (Sandbox Code Playgroud)

然后发送这样的帖子请求

// 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"));
Run Code Online (Sandbox Code Playgroud)

  • 美丽的答案。 (2认同)

Ric*_*der 5


Saj*_*dan 5

只需使用以下库。

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 = jsonData.CustomerObj;
        var customerObj = customerObjJson.ToObject<Customer>();
        return customerObj;
    }
Run Code Online (Sandbox Code Playgroud)