使用HttpClient调用WebAPI接口,含WebAPI端示例

API端:

using log4net;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;

namespace WebApi.Controllers
{
    public class DefaultController : ApiController
    {
        private ILog log = log4net.LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        IList<menu> List = new List<menu>();


        public DefaultController()
        {
            for (int i = 1; i <= 2; i++)
            {
                List.Add(new menu { menuId = i, menuName = "Menu" + i });
            }
        }


        // GET: api/Default
        public IEnumerable<menu> Get()
        {
            return List;
        }

        // GET: api/Default/5
        public menu Get(int id)
        {
            try
            {
                return List.FirstOrDefault(m => m.menuId == id);
            }
            catch(Exception e)
            {
                return new menu();
            }
        }

        // POST: api/Default
        //public void Post(int id,[FromBody]menu menu)
        //{
        //    log.Info(menu.menuName);
        //}

        // PUT: api/Default/5
        public void Put(int id, string guid, [FromBody]string value)
        {
            log.InfoFormat("PUT  id:{0},value:{1},guid:{2}", id, value, guid);
        }

        // DELETE: api/Default/5
        public void Delete(int id)
        {
            log.Info(id);
        }

        public IHttpActionResult UploadFile()
        {
            //log.Info(id);
            log.Info(HttpContext.Current.Request.Form["qq"]);
            var file = HttpContext.Current.Request.Files[0];
            file.SaveAs(HttpContext.Current.Server.MapPath("/test.jpg"));
            return Ok<string>("test");
        }
    }

    public class menu
    {
        public int menuId { get; set; }
        public string menuName { get; set; }
    }
}

调用端:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Net.Http;
using System.Text;
using System.Net.Http.Headers;
using System.IO;
using Newtonsoft.Json;

namespace WebApi.Controllers
{
    public class ClientController : Controller
    {
        // GET: Client
        public ActionResult Index()
        {
           
            //HttpClient client = new HttpClient();
            //string Url = "http://localhost:33495/api/default/";

            #region 原始方式调用
            //StringContent方式调用
            //var result = client.PostAsync(Url, new StringContent("111", Encoding.UTF8, "application/json")).Result;

            //ByteArrayContent方式
            //var data = Encoding.UTF8.GetBytes("\"ddd\"");
            //data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new menu { menuId = 1, menuName = "33333" }));
            //data = Encoding.UTF8.GetBytes("{menuId:1,menuName:333}");
            //var content = new ByteArrayContent(data);
            //content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
            //var result_byte = client.PostAsync(Url, content).Result;

            //PostAsJsonAsync方式
            //client.PostAsJsonAsync(Url, "ss");
            #endregion

            #region 多参数传参
            //client.PutAsJsonAsync(string.Format("{0}{1}?guid={2}", Url, 5, Guid.NewGuid()), "test");
            #endregion

            #region 服务端上传图片
            //服务端上传图片
            //using (HttpClient client = new HttpClient())
            //{
            //    var content = new MultipartFormDataContent();
            //    //添加字符串参数,参数名为qq
            //    content.Add(new StringContent("123456"), "qq");

            //    string path = Server.MapPath("/Images/test.jpg");
            //    //添加文件参数,参数名为files,文件名为123.png
            //    content.Add(new ByteArrayContent(System.IO.File.ReadAllBytes(path)), "file", "test.jpg");

            //    var requestUri = "http://localhost:33495/api/default/";
            //    var result = client.PostAsync(requestUri, content).Result.Content.ReadAsStringAsync().Result;

            //    Response.Write(result);
            //}
            #endregion

            return null;
        }

        public ActionResult HTML()
        {
            return View();
        }

        public ActionResult Upload()
        {
            return View();
        }
    }
}

HTML(AJAX上传)

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>webapi上传图片</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
    <h2>webapi create</h2>
    <div>
        <form name="form1" method="post" enctype="multipart/form-data">
            <div>
                <label for="image1">Image</label>
                <input type="text" name="test" id="test" />
            </div>
            <div>
                <label for="image1">Image</label>
                <input type="file" name="photo" id="photo" />
            </div>
            <div>
                <input type="button" value="ajax upload" id="btnUpload" />
            </div>
            <div>
                <img id="phptoPic" width="200" />
            </div>
        </form>
    </div>
    <script type="text/javascript">
        $(function () {
            $("#btnUpload").click(function () {
                var formData = new FormData();
                formData.append("photo", $("#photo")[0].files[0]);
                $.ajax({
                    url: '/api/default/UploadFile',
                    type: 'post',
                    data: formData,
                    contentType: false,
                    processData: false,
                    success: function (res) {
                        //console.log(res);
                        if (res == "test") {
                            $("#phptoPic").attr("src", res.url)
                        } else {
                            alert(res.message)
                        }
                    }
                })
            })
        })
    </script>
</body>
</html>

微软官网示例:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Product App</title>
</head>
<body>

    <div>
        <h2>All Products</h2>
        <ul id="products" />
    </div>
    <div>
        <h2>Search by ID</h2>
        <input type="text" id="prodId" size="5" />
        <input type="button" value="Search" onclick="find();" />
        <p id="product" />
    </div>


    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script>
    var uri = '/api/Default';

    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
          });
    });

    function formatItem(item) {
      return item.menuId + item.menuName;
    }

    function find() {
      var id = $('#prodId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#product').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
          });
    }
    </script>
</body>
</html>

 

posted on 2019-09-20 15:46  静以修身俭以养德  阅读(1545)  评论(0编辑  收藏  举报

导航