WebAPI的Get和Post访问

Posted 月明星惜

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了WebAPI的Get和Post访问相关的知识,希望对你有一定的参考价值。

        /// <summary>
        /// MVC 调用webapi接口返回框架快捷按钮和一级菜单(Get)
        /// </summary>
        /// <param name="userId">登录名</param>
        /// <param name="sysShortName">系统简称 如:crm scm ssn</param>
        /// <param name="pwd">密码</param>
        /// <param name="factoryId">工厂编号</param>
        /// <returns></returns>
        public ShortcutResult ReturnShortcutBtn(string userId, string sysShortName, string pwd, string factoryId)
        {
            ShortcutResult shrotcut_result = new ShortcutResult();
            try
            {
                using (var httpClient = new HttpClient())
                {
                    string WebAPIUrl = string.Format(ReturnAppSettingValue("OAShortcut") + "?sysShortName={0}&uid={1}&pwd={2}&factoryId={3}", sysShortName, userId, pwd, factoryId);

                    var task = httpClient.GetAsync(WebAPIUrl);
                    var result = task.Result.Content.ReadAsStringAsync().Result;
                    if (task.Result.IsSuccessStatusCode == false)
                        throw new Exception("接口访问失败:" + task.Result.StatusCode);

                    MenuResult list = JsonConvert.DeserializeObject<MenuResult>(result);

                    if (list != null && list.Success)
                    {
                        var firstMenu = JsonConvert.DeserializeObject<List<FirstLvlMenu>>(list.Menu).OrderBy(t => t.Menu_order).ToList();
                        var btns = JsonConvert.DeserializeObject<List<ShortCutBtn>>(list.Button).OrderBy(t => t.Btn_Order).ToList();

                        shrotcut_result = new ShortcutResult(firstMenu, btns);
                    }
                    else
                    {
                        throw new Exception("WebAPI无值返回或访问失败");
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, LogEnum.Error);
                throw ex;
            }

            return shrotcut_result;
        }

  

        /// <summary>
        /// MVC 调用webapi接口返回退货单详情页操作按钮(Post)
        /// </summary>
        /// <returns></returns>
        public MenuCommand ReturnCommandBtn(string userId, string menuId, string pwd, string factoryId)
        {
            MenuCommand menuCmd_result = new MenuCommand();
            try
            {
                using (var httpClient = new HttpClient())
                {
                    string WebAPIUrl = ReturnAppSettingValue("ReturnGoodsCommandBtn");
                    HttpContent postContent = new FormUrlEncodedContent(new Dictionary<string, string>()
                    {
                       {"menuId",menuId},
                       {"uid",userId},
                       {"pwd",pwd},
                       {"factoryId",factoryId}
                    });
                    var task = httpClient.PostAsync(WebAPIUrl, postContent);
                    var result = task.Result.Content.ReadAsStringAsync().Result;
                    if (task.Result.IsSuccessStatusCode == false)
                        throw new Exception("接口访问失败:" + task.Result.StatusCode);

                    if (!string.IsNullOrEmpty(result))
                    {
                        menuCmd_result = JsonConvert.DeserializeObject<MenuCommand>(result);
                    }
                }
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, LogEnum.Error);
                throw ex;
            }

            return menuCmd_result;
        }

  

        //传递Json格式串

     /// <summary>
        /// 返回Token
        /// </summary>
        /// <returns></returns>
        public APIToken ReturnToken(string userId, string pwd)
        {
            APIToken token = new APIToken();
            try
            {
                string WebAPIUrl = ReturnAppSettingValue("ReturnGoodsToken"); 
                string postData = "{\"UserId\":\"" + userId + "\",\"PassWord\": \"" + pwd + "\"}";

                HttpContent httpContent = new StringContent(postData);
                httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpClient httpClient = new HttpClient();

                HttpResponseMessage response = httpClient.PostAsync(WebAPIUrl, httpContent).Result;

                if (response.IsSuccessStatusCode)
                {
                    string responseJson = response.Content.ReadAsStringAsync().Result;
                    token = JsonConvert.DeserializeObject<APIToken>(responseJson);
                }
                else
                {

                } 
                
            }
            catch (Exception ex)
            {
                WriteLog(ex.Message, LogEnum.Error);
                throw ex;
            }
            return token;
        }

  

以上是关于WebAPI的Get和Post访问的主要内容,如果未能解决你的问题,请参考以下文章

JQuery Ajax POST/GET 请求至 ASP.NET WebAPI

在自定义授权 MVC4 Web Api 中访问 post 或 get 参数

怎样操作WebAPI接口

怎样操作WebAPI接口

webapi的post和get请求总结

[转发]MVC WebApi get和post请求