如何创建web api并从客户端应用程序中消费?

时间:2016-08-12 12:39:01

标签: asp.net asp.net-web-api

我是Asp.net Web API开发的新手。我想使用Asp.Net Web API开发Web API Restful服务并使用客户端应用程序。 那么,如何在服务器中创建Http动词--GET,POST,PUT和DELETE方法,并在Asp.net应用程序中使用httpclient进行消费。

提前致谢。

1 个答案:

答案 0 :(得分:0)

创建Asp.net Web API应用程序。逐步解释两个应用程序。

1.Asp.Net Web API创建 2.在Asp.Net MVC应用程序中使用Asp.Net Web API

Asp.Net Web API创建

在visual studio中 - 创建新项目 - > Asp.Net Web应用程序 - > Web API [更改身份验证 - >无身份验证] - >单击“确定”

WebApiConfig.cs中的小代码更改

默认

        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

添加以下代码:

        config.Routes.MapHttpRoute(
        name: "ActionApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
        );

这个Web Api应用程序访问库函数使用bellow文件及其从数据库中获取数据。

  • SettingsBO
  • ShipmentBO

我已经开发了GET和POST方法功能

namespace MyFirstWebAPI.Controllers
{

[RoutePrefix("api/Product")]
public class ProductController : ApiController
{
    [HttpGet]
    [Route("GetAllPorts")]
    public async Task<IEnumerable<Port>> GetAllPorts()
    {
        try
        {
            IEnumerable<Port> port = await SettingsBO.GetPortAsync();
            return port;
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }

    [HttpGet]
    [Route("GetShipmentDetails/{shipmentLId}/{orderid}")]
    public async Task<ShipmentLegViewModel> GetShipmentDetails(string shipmentLId, string orderid)
    {
        try
        {
            ShipmentLegViewModel shipmentDet = await ShipmentBO.GetSegmentLegDetailsAsync(shipmentLId, orderid);
            return shipmentDet;
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }

    [HttpPost]
    [Route("UpdatePort")]
    public async Task<string> UpdatePort(List<PortUpdate> port, string Id, string portStatusId)
    {
        try
        {
            return await SettingsBO.UpdateItemAsync(Id, port, portStatusId);
        }
        catch (Exception ex)
        {
            var err = ex.Message.ToString().Replace("\n", "N^^").Replace("\r", "R^^");
            var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
            {
                Content = new StringContent(string.Format("Error Message = {0}", err)),
                ReasonPhrase = err
            };
            throw new HttpResponseException(resp);
        }
    }
}

}

上面的代码有助于创建Asp.Net Web API应用程序。使用波纹管结构建立并运行应用程序。

网址:http://localhost:4314/api/Product/GetAllPorts

2.在Asp.Net MVC应用程序中使用Asp.Net Web API

我已经创建了一个Asp.Net MVC应用程序。

您应该为客户端应用添加web api包

  

安装包Microsoft.AspNet.WebApi.Client

创建一个特定的类[Webservice.cs]来访问Web API数据。鉴于以下代码

namespace WebAPI_Client.CNHService
{
public static class WebService<T> where T : class
{
    public static string appSettings = ConfigurationManager.AppSettings["ServiceURL"];

    public static IEnumerable<T> GetDataFromService(string Method, string param = "")
    {
        WebClient client = new WebClient();
        try
        {
            var data = client.DownloadData(appSettings + Method + param);
            var stream = new System.IO.MemoryStream(data);
            var obj = new DataContractJsonSerializer(typeof(IEnumerable<T>));
            var result = obj.ReadObject(stream);
            IEnumerable<T> Ts = (IEnumerable<T>)result;
            return Ts;
        }
        catch (WebException wex)
        {
            throw;
        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public static T GetDataFromService_SingleCollection(string Method, string param = "")
    {
        try
        {
            var client = new WebClient();
            var data = client.DownloadData(appSettings + Method + param);
            var stream = new System.IO.MemoryStream(data);
            var obj = new DataContractJsonSerializer(typeof(T));
            var result = obj.ReadObject(stream);
            T Ts = (T)result;
            return Ts;
        }
        catch (Exception ex)
        {
            throw;
        }
    }


    public static async Task<T> GetShipmentDetails(string shipmentLId,string orderid)
    {
        Stream stream = null;
        T Ts = null;
        string url = "http://localhost:4314/api/Product/GetShipmentDetails/5462f4e3e4b09e0d94f5c9a2/5462f4e2e4b09e0d94f5c9a1";
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsByteArrayAsync();
                    var stre = new System.IO.MemoryStream(data);
                    var obj1 = new DataContractJsonSerializer(typeof(IEnumerable<T>));
                    var result = obj1.ReadObject(stre);
                    Ts = (T)result;
                }
                else
                {
                    stream = await response.Content.ReadAsStreamAsync();
                    var error = await response.Content.ReadAsStringAsync();
                }
                return Ts;
            }
        }
        catch (Exception ex)
        {

        }
        return Ts;
    }

    public static async Task<IEnumerable<T>> GetPorts()
    {
        Stream stream = null;
        IEnumerable<T> Ts = null;
        string url = "http://localhost:4314/api/Product/GetAllPorts";
        try
        {
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                HttpResponseMessage response = await client.GetAsync(url);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsByteArrayAsync();
                    var stre = new System.IO.MemoryStream(data);
                    var obj1 = new DataContractJsonSerializer(typeof(IEnumerable<T>));
                    var result = obj1.ReadObject(stre);
                    Ts = (IEnumerable<T>)result;
                }
                else
                {
                    stream = await response.Content.ReadAsStreamAsync();
                    var error = await response.Content.ReadAsStringAsync();
                }
                return Ts;
            }
        }
        catch (Exception ex)
        {

        }
        return Ts;
    }

    public static async Task<IEnumerable<T>> GetDataFromService_Update(string Method, List<Port> portData, string param = "")
    {
        try
        {
            string requestUri = Method + param;
            string url = "http://localhost:4314/";
            IEnumerable<T> Ts = null;
            using (HttpClient client = new HttpClient())
            {
                client.BaseAddress = new Uri(url);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await client.PostAsJsonAsync(requestUri, portData);
                if (response.IsSuccessStatusCode)
                {
                    var res = await response.Content.ReadAsStringAsync();
                }
                else
                {
                    var error = await response.Content.ReadAsStringAsync();
                }
            }
            return Ts;
        }
        catch (Exception ex)
        {
            throw;
        }
    }
}

}

控制器代码

对于GET和POST方法

 public class HomeController : Controller
{
    public async Task<ActionResult> Index()
    {
         //GET Method      
         IEnumerable<Port> portq = await CNHService.WebService<Port>.GetPorts();
         //POST Method      
         List<Port> port = portq.ToList<Port>();
         IEnumerable<string> resUpdate = await CNHService.WebService<string>.GetDataFromService_Update("api/Product/UpdatePort", port, "?Id=5462f4d8e4b09e0d94f5c96f&portStatusId=5462f4d8e4b09e0d94f5c96c");
    }
}

上面的代码可以很好地获取和发布方法。

此代码对Web API应用程序开发更有帮助