webapi 获取json数据

一般的我们可以直接使用参数来接受,这个就不多介绍了

        [HttpGet]
        public IHttpActionResult Test2([FromUri]string name)
        {
            throw new Exception("嘻嘻嘻");
        }


        [HttpPost]
        public IHttpActionResult Test3([FromBody]string name)
        {
            throw new Exception("嘻嘻嘻");
        }

针对post接口:

现在一般使用json来传递参数

①使用参数名来接受,这样显示不管你是传递json字符串还是json对象都是介绍不到的

 [HttpPost]
        public IHttpActionResult Test4([FromBody]string json)
        {
            throw new Exception("嘻嘻嘻");
        }

②稍微改动下,把参数类型换成objct,这样我们不管是传递json对象和字符串都是能够接受到的

 [HttpPost]
        public IHttpActionResult Test4([FromBody]object json)
        {
            throw new Exception("嘻嘻嘻");
        }

json对象;

json字符串:

 列如:测试我们的objct都是有值的

     /// <summary>
        /// 厕所基本信息
        /// </summary>
        /// <param name="json">
        ///{"CsNum":"A18080180","CsName":"厕所名称","CoordX":"121.151515","CoordY":"30.545454","Rank":"一级","CumnlatieNum":8848}
        /// </param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult CsInfo([FromBody]object json)
        {
            try
            {
                ToiletInfoInDto dto = JsonConvert.DeserializeObject<ToiletInfoInDto>(json.ToString());
                return Ok(new { errcode = 0, data = "请求成功" });
            }
            catch (Exception ex)
            {
                return Ok(new { errcode = -1, errmsg = ex.Message });
            }
        }

 ③提升,mvc中也可以写接口,我们肯定使用过流接受过参数,那webapi中同样是可以的

mvc中可以直接写:

 string json2 = new StreamReader(Request.InputStream).ReadToEnd();

webapi中没有 HttpContext这个,我们可以引用进行使用

  //引用 using System.Web;
                string json2 = new StreamReader(HttpContext.Current.Request.InputStream).ReadToEnd();

webapi中我们使用request强制同步获取数据,显示获取不到

   //强制同步获取不到数据
                string aa = this.Request.Content.ReadAsStringAsync().GetAwaiter().GetResult();

推荐:

最后我们可以使用异步来用:这样就能读到数据

     [HttpPost]
        public async Task<IHttpActionResult> TestAsync()
        {
            string aa = await this.Request.Content.ReadAsStringAsync();
            return Ok("12");
        }

总结:

1:Object来进行转型做

2:异步获取数据

题外:我们一般都会准备一个Dto来接受我们的json对象,如果你不想这样写,也可以使用JObject来用。

猜你喜欢

转载自www.cnblogs.com/Sea1ee/p/10438838.html
今日推荐