65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 C#.NET 或 Xamarin 应用开发以编程方式调用 Web 服务

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.27/5 (7投票s)

2017年4月13日

CPOL

4分钟阅读

viewsIcon

50228

如何以编程方式调用和使用 C#.NET 中的 Web 服务

引言

本文对于将要使用 ASP.NET C# Web 服务/Web API 服务开发项目的各位非常有帮助。本文对于正在使用 Xamarin:移动应用开发和应用创建的各位也很有帮助。

这篇文章将事情简化了。您只需要准备好您的服务 URL,发送数据(如果是 POST 服务)。

最后,您将获得 JSON 字符串作为输出,只需根据您的 JSON 格式化字符串创建类,然后根据您的需求使用数据。

移动应用程序开发人员可以使用所有这些方法,只是他们不需要 datatable,他们可以只获取列表,然后执行他们的操作。

对于只想获取现成代码的人来说,他们将传递 URL 和过滤参数,然后下载 DLL 并按给定方式使用。

那些不想依赖 DLL 的人可以使用下面的代码。

创建 Web 服务

using WebApi.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Caching;
using System.Web.Http;
using System.Web.Script.Serialization;

namespace WebApi.Controllers
{
    public class HomeController : ApiController
    {

        [HttpPost ]
        public HttpResponseMessage GetData(App_DataFilters ObjDigFilters)
        {
            Exception _ex = null;
            OutputResult _result = new OutputResult();
            DataView dv = new DataView();

            try
            {
                Dal_Data objDal = new Dal_Data();
                dv = objDal.GetData(out _ex).AsDataView();              

                _result.Data = dv.ToTable();

                if (_ex != null)
                {
                    _result.IsSucceed = false;
                    _result.ExceptionDetails = _ex;
                }
                else { _result.IsSucceed = true; }

            }
            catch (Exception ex)
            {
                _result.IsSucceed = false;
                _result.ExceptionDetails = ex;
                return Request.CreateResponse(HttpStatusCode.InternalServerError, _result);
            }

            return Request.CreateResponse(HttpStatusCode.OK, _result);
        }
}
}

 public class App_DataFilters
    {
        public string ProductName{ get; set; }
        public string Code { get; set; }
        public string Description { get; set; }
        public string CodesetName { get; set; }
         
    }

    public class OutputResult
    {
        public bool IsSucceed { get; set; } = false;
        public string Comment { get; set; } = string.Empty;
        public Exception ExceptionDetails { get; set; }
        public DataTable Data { get; set; }
    }

使用 Web 服务

public class MyClass
    {
        public async Task<OutputResult> GetData(App_DataFilters obj)
        {
            OutputResult _OutputResult = new OutputResult();
            JavaScriptSerializer _Serializer = new JavaScriptSerializer();
            try
            {               
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri("https://:41315/");
                var json = _Serializer.Serialize(obj);
                HttpContent content = 
                      new StringContent(json, Encoding.UTF8, "application/json");
                HttpResponseMessage response = 
                      await client.PostAsync("api/Home/GetData", content);

                var Data = response.Content.ReadAsAsync<OutputResult>();

                return Data.Result;
            }
            catch (Exception ex)
            {
                _OutputResult.IsSucceed = false;
                _OutputResult.ExceptionDetails = ex;                 
            }
            return _OutputResult;
        }
}
那些想要使用现成代码的人可以按照下面描述的方式进行。下载 DLL,只传递所需的变量即可获得输出。

背景

为此,您需要下载 ImportJson.dllRestSharp.dllNewtonsoft dll。将 ImportJson DLL 添加到您的项目中。

如何添加?

  1. 下载 ImportJson DLL。
  2. 右键单击“引用”。
  3. 单击“浏览”按钮,然后转到 DLL 下载的路径。

从以下位置下载 ImportJson

Using the Code

调用简单的 GET 方法

示例:用于获取访问令牌的 GET 服务

URL: http://test.mydomin.com/ipos/oauth/api/?grantType=password&username=userName&password=Password@321

使用下面的函数获取 JSON 输出

/// <summary>
/// Simple Get method
/// </summary>
/// <returns> Json formatted data </returns>
   
public string GetJsonData1()
{
    IOperations _Obj = ClsOperations.GetOperations();
    string url = "http://test.mydomin.com/ipos/oauth/api/
     ?grantType=password&username=userName&password=Password@321";
     string jsonResult = _Obj.GetJsonResult(url);
    return jsonResult;
}

上面的函数将返回如下所示的 JSON 格式的 字符串

{
       "success": true,
       "count": 1,
       "totalCount": 1,
       "access_token": "70f1f689-457e-49da-8858-87f478240051",
       "errors": null
}

如何使用:假设我想将访问令牌分配给 Label Text,然后创建如下类

public class ClsAccessToken
{
    public bool success { get; set; }
    public int count { get; set; }
    public int totalCount { get; set; }
    public string access_token { get; set; }
    public object errors { get; set; }
}
 
string _res = GetJsonData1();
ClsAccessToken obj = (JsonConvert.DeserializeObject<ClsAccessToken>(_res));

现在您将从类对象中获取所有内容。以下代码将把访问令牌值分配给标签。

Label1.Text=obj.access_token;

调用带有多值/列表/枚举/表格 JSON 数据的简单 GET 方法

ID 名称 城市
1 Amol Buldana
2 Ram Nagpur
3 Krishna Amaravati

现在假设您的 JSON 数据包含多个或表格格式的数据,如下所示

[{
                "ID": "1",
                "Name": "Amol",
                "City": "Buldana"
}, {
                "ID": "2",
                "Name": "Ram",
                "City": "Nagpur"
}, {
                "ID": "3",
                "Name": "Krishna",
                "City": "Amaravati"
}]

您希望将其放入 List 或显示在 Gridview 中,则过程如下

创建类并获取详细信息

public class ClsEmployee
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}
protected void GetData()
{     
    string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url);
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
           <ClsEmployee>(enumerator.Current.ToString()));
    }
// Mobile developers use the lst as list of List<ClsEmployee>
DataTable dt = CommonServiceCall.ToDataTable(lst);
// For list to datatable take reference from internet
// E.g. http://stackoverflow.com/questions/18100783/how-to-convert-a-list-into-data-table
//Dot net developers can perform operations on datatable
}

调用带有数据 POST/POST 方法的 Web 服务

如果您只想显示某个 employee 的详细信息,例如,从上面的示例中,我们将只显示第一个 employee 的信息,假设 ID=1

ID 名称 城市
1 Amol Buldana
protected void GetDataByParameter()
{
    string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    Dictionary<string, object> objDec = new Dictionary<string, object>();
    objDec.Add("@ID", "1");
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url,objDec );
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
        <ClsEmployee>(enumerator.Current.ToString()));
    }
 
    DataTable dt = CommonServiceCall.ToDataTable(lst);
}

调用带有数据 POST/POST 方法的 Web 服务(POST 数据采用 JSON 格式)

ID 名称 城市
1 Amol Buldana
/// <summary>
/// Post Method with Input/ data to post in JSON format
/// </summary>
/// <returns> Json formatted data </returns>
 
protected void GetDataByjsonParameter()
{
      string url = 
      "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
      IOperations obj = ClsOperations.GetOperations();
      string InputJson = "{ \"ID\": \"1\" }";
      IEnumerator enumerator = obj.GetJsonEnumerableResult(url, null ,InputJson );
      List<ClsEmployee> lst = new List<ClsEmployee>();
      while (enumerator.MoveNext())
      {
          lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
          <ClsEmployee>(enumerator.Current.ToString()));
      }
      DataTable dt = CommonServiceCall.ToDataTable(lst);
}

调用 Xamarin 应用/移动开发者 Web 服务,使用带有数据 POST/POST 方法(POST 数据采用 JSON 格式)

ID 名称 城市
1 Amol Buldana
protected List<ClsEmployee> GetDataByjsonParameterXamrine()
{
    string url = 
    "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
    IOperations obj = ClsOperations.GetOperations();
    JSONObject JSONObj = new JSONObject();
    JSONObj.put("ID", "1");
    string InputJson = JSONObj.ToString();
    IEnumerator enumerator = obj.GetJsonEnumerableResult(url, null, InputJson);
    List<ClsEmployee> lst = new List<ClsEmployee>();
    while (enumerator.MoveNext())
    {
        lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject
        <ClsEmployee>(enumerator.Current.ToString()));
    }
            
    return lst;
}

强制将方法设置为 GET 或 POST

在此,您可以看到,直到目前为止,您无需担心 GETPOST 方法,因为默认情况下,如果单个 URL 返回数据,则表示服务为 GET 类型,如果 URL 带有参数,则为 POST。但有时,可能会发生服务只有一个 URL,但仍然是 POST 类型的情况。在这种情况下,我们可以使用下面的函数

public string GetJsonDataByForcefullyPOST()
{
   IOperations _Obj = ClsOperations.GetOperations();
   string url = "http://test.mydomin.com/ipos/oauth/api/
   ?grantType=password&username=userName&password=Password@321";
   string jsonResult = _Obj.GetJsonResult (url,null,null,ServiceType.POST );        
   return jsonResult;
}

从 JSON 字符串转换为类对象/列表/DataTable

希望到目前为止,本文对您非常有帮助,现在我将告诉您如何利用上述代码处理各种类型的 JSON 格式数据并使用它们。这样,在开发过程中,您就不需要从外部引用,因为所有内容都将在这里提供。

类型 1

处理简单的 JSON 数据

示例:如果 JSON 结果如下所示

{
                "ID": "1",
                "Name": "Amol Khandagale",
                "City": "Buldana"
}

然后可以如下处理和使用

 //Handling simple JSON
        protected void HandleSimpleJSON()
        {
            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
            IOperations obj = ClsOperations.GetOperations();
            ClsEmployee objEmp = new ClsEmployee();
            String _res=obj.GetJsonResult(url);
            objEmp = Newtonsoft.Json.JsonConvert.DeserializeObject<ClsEmployee>(_res);
            string EmpID = objEmp.ID; // Gives result as 1
            string EmpName = objEmp.Name; //  Gives result as Amol
            string EmpCity = objEmp.City; //  Gives result as Buldana
        }

类型 2

处理包含多个值的简单 JSON 数据

示例:如果 JSON 格式如下

[{
                "ID": "1",
                "Name": "Amol",
                "City": "Buldana"
}, {
                "ID": "2",
                "Name": "Ram",
                "City": "Nagpur"
}, {
                "ID": "3",
                "Name": "Krishna",
                "City": "Amaravati"
}]

然后可以如下处理和使用

//Handling simple JSON object having multiple values
protected void GetAllEmployeeDetails()
        { 
            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
            IOperations obj = ClsOperations.GetOperations();
            IEnumerator enumerator = obj.GetJsonEnumerableResult(url);
            List<ClsEmployee> lst = new List<ClsEmployee>();
            while (enumerator.MoveNext())
            {
                lst.Add(Newtonsoft.Json.JsonConvert.DeserializeObject<ClsEmployee>
                       (enumerator.Current.ToString()));
            }

 /* Here we get List of Employees, you can convert it to DataTable,
    IEnumerable, LINQ object and can perform various operations on it. */
        }

类型 3

处理稍微复杂的 JSON 数据

示例:如果 JSON 格式如下

{
                "Status": "Success",
                "Message": "Success",
                "TotalCount": "3",
                "Data": [{
                                "ID": "1",
                                "Name": "Amol",
                                "City": "Buldana"
                }, {
                                "ID": "2",
                                "Name": "Ram",
                                "City": "Nagpur"
                }, {
                                "ID": "3",
                                "Name": "Krishna",
                                "City": "Amaravati"
                }]
}

然后可以如下处理和使用

这里,JSON 对象相当复杂,可以说它是一个嵌套对象。您只需要找出有多少嵌套对象,并相应地创建类。在此示例中,我们有两个对象

  1. 包含四个实体的对象
    1. 状态
    2. Message
    3. TotalCount
    4. Data

      Data”实体又包含三个实体,即:

      1. ID
      2. 名称
      3. 城市

因此,我们需要如下两个类

public class ClsEmployee
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}
public class ClsEmployeeDetails
{
    public string Status { get; set; }
    public string Message { get; set; }
    public string TotalCount { get; set; }
    public List< ClsEmployee > Data { get; set; }
}
//Handling little JSON object having multiple values
protected DataTable GetEmployeeDetails()
        {
            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
            IOperations obj = ClsOperations.GetOperations();          
            ClsEmployee objEmp = new ClsEmployee();
            String _res=obj.GetJsonResult(url);
            ClsEmployeeDetails  objEmpData = 
               JsonConvert.DeserializeObject< ClsEmployeeDetails >(_res);
            List< ClsEmployee> lst1 = new List< ClsEmployee >();
            if (objEmpData.data != null)
            {
                    foreach (ClsEmployee i in objEmpData.data)
                    {
                        lst1.Add(i);
                    }
            }
        } 

类型 4

处理复杂的 JSON 数据

示例:如果 JSON 格式如下

{
                "Status": "Success",
                "Message": "Success",
                "TotalCount": "3",
                "Data": [{
                                "ID": "1",
                                "Name": "Amol",
                                "City": "Buldana",
                                "Skills": [{
                                                "Subject": "ASP.NET"
                                }, {
                                                "Subject": "C#"
                                }]
                }, {
                                "ID": "2",
                                "Name": "Ram",
                                "City": "Nagpur",
                                "Skills": [{
                                                "Subject": "C#"
                                }]
                }, {
                                "ID": "3",
                                "Name": "Krishna",
                                "City": "Amaravati",
                                "Skills": [{
                                                "Subject": "ASP.NET"
                                }, {
                                                "Subject": "C#"
                                }, {
                                                "Subject": "SQL Server"
                                }]
                }]
}

现在这里的嵌套又增加了,因此结构变得有些复杂。这里在 employee 详细信息中,有多个 employee,并且每个 employee 都有多个技能,现在我们需要创建三个类,如下所示:

public class ClsSkills
{
    public string Subject { get; set; }
}
public class ClsEmployee
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
    public List<ClsSkills> Skills { get; set; }
}
public class ClsEmployeeDetails
{
    public string Status { get; set; }
    public string Message { get; set; }
    public string TotalCount { get; set; }
    public List<ClsEmployee> Data { get; set; }
}

然后可以如下处理和使用

protected void   GetEmployeeDetails()
        {
            string url = "http://test.mydomin.com/ipos/oauth/api/GetEmployeeData";
            IOperations obj = ClsOperations.GetOperations();
            ClsEmployee objEmp = new ClsEmployee();
            String _res=obj.GetJsonResult(url);          

            ClsEmployeeDetails objData = 
               JsonConvert.DeserializeObject<ClsEmployeeDetails>(GetJsonString());
            List<ClsEmployee> lst = new List<ClsEmployee>();
            List<ClsSkills> lst1 = new List<ClsSkills>();
            if (objData.Data != null)
            {
                foreach (ClsEmployee e in objData.Data)
                {
                    lst.Add(e);
                    foreach (ClsSkills i in e.Skills )
                    {
                        lst1.Add(i);
                    } 
                }
            }

            /* Now we can make use of these lists lst, lst1, 
               objData and can perform your required operations */
        }

通过这种方式,只需参考这种嵌套,希望您现在可以处理任何 JSON 数据格式。

如果您正在使用 ASP.NET、C# 和 Web 服务或 Xamarin 开发应用程序,本文将在整个项目中为您提供帮助。我认为您不需要从外部获取任何引用。

如果您有任何建议/更改,请在下方留言。

历史

  • 2020 年 1 月 3 日:初始版本
© . All rights reserved.