C#工具:利用HttpClient调用WebApi

可以利用HttpClient来进行Web Api的调用。由于WebA Api的调用本质上就是一次普通的发送请求与接收响应的过程,

所有HttpClient其实可以作为一般意义上发送HTTP请求的工具。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace 自己的名称空间
{
    public class ApiHelper
    {
        /// <summary>
        /// api调用方法/注意一下API地址
        /// </summary>
        /// <param name="controllerName">控制器名称--自己所需调用的控制器名称</param>
        /// <param name="overb">请求方式--get-post-delete-put</param>
        /// <param name="action">方法名称--如需一个Id(方法名/ID)(方法名/?ID)根据你的API灵活运用</param>
        /// <param name="obj">方法参数--如提交操作传整个对象</param>
        /// <returns>json字符串--可以反序列化成你想要的</returns>
        public static string GetApiMethod(string controllerName, string overb, string action, object obj = null)
        {
            Task<HttpResponseMessage> task = null;
            string json = "";
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:****/api/" + controllerName + "/");
            switch (overb)
            {
                case "get":
                    task = client.GetAsync(action);
                    break;
                case "post":
                    task = client.PostAsJsonAsync(action, obj);
                    break;
                case "delete":
                    task = client.DeleteAsync(action);
                    break;
                case "put":
                    task = client.PutAsJsonAsync(action, obj);
                    break;
                default:
                    break;
            }
            task.Wait();
            var response = task.Result;
            if (response.IsSuccessStatusCode)
            {
                var read = response.Content.ReadAsStringAsync();
                read.Wait();
                json = read.Result;
            }
            return json;
        }
    }
}

可能需要以下引用集:

System.Net.Http.Formatting.dll

System.Web.Http.dll

posted on 2019-03-29 15:56  刘元蛟  阅读(3276)  评论(0编辑  收藏  举报

导航