请求http服务
①服务方法 [HttpGet]//get服务 public JsonResult GetUserName(int id) { try { IXiao_UserBLL bll = new Xiao_UserBLL(); var model = bll.GetUserById(ConnectPool.connect, id); return Json(model.Name,JsonRequestBehavior.AllowGet); } catch (Exception) { return null; } } [HttpPost] //post服务 public JsonResult GetUserPost(int id) { try { IXiao_UserBLL bll = new Xiao_UserBLL(); var model = bll.GetUserById(ConnectPool.connect, id); return Json(model, JsonRequestBehavior.AllowGet); } catch (Exception) { return null; } }
服务需要发布后才可以请求的到
②Get请求服务 public string Login(int userid) { try { var id = userid; var url = "http://www.xiaoyaodijun.club/home/GetUserName/" + id; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "GET"; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string json = streamReader.ReadToEnd(); return null; } catch { return "error"; } }
③Post请求服务 public string GetOneUser(int userid) { try { var url = "http://www.xiaoyaodijun.club/home/GetUserPost/"; var param = "id="+userid; byte[] bs = Encoding.ASCII.GetBytes(param); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; //这个标识文件类型。application/octet-stream表示二进制数据。 request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = bs.Length; using (Stream str = request.GetRequestStream()) { str.Write(bs, 0, bs.Length); } using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { Stream responseStream = response.GetResponseStream(); StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8); string json = streamReader.ReadToEnd(); } return null; } catch { return "error"; } }