一、webapi創建 1、創建項目 我使用的是VS2015,點開新建項目,安裝如下操作執行: . 2、設置路由 config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id} ...
一、webapi創建
1、創建項目
我使用的是VS2015,點開新建項目,安裝如下操作執行:
.
2、設置路由
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
3、設置控制器
在Controllers 文件夾下創建一個示例控制器: apiController
至此webapi創建完成。
二、webapi訪問
這裡主要說明get和post訪問方法。瀏覽器預設使用GET請求方式,如果要使用POST請求,需要下載插件,如火狐的RESTclient,ctrl+shift+A可進入下載。
[HttpGet]:表示使用GET訪問;(同時GET方式訪問可以給函數命名為Get***)
[HttpPost]:表示使用POST訪問;
[AcceptVerbs("GET", "POST")]:POST和GET方法都支持;
1、Get請求
[HttpGet] public HttpResponseMessage GetSendRequest(string mo) { string rStr = ""; HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url); webRequest.Method = "GET"; HttpWebResponse webResponse; try { //如果沒有try...catch語句訪問頁面出現錯誤時本句會顯示錯誤,使程式無法運行 webResponse = (HttpWebResponse)webRequest.GetResponse(); //請求頁面信息 } catch (WebException ex) { webResponse = (HttpWebResponse)ex.Response; //獲得錯誤發生時候伺服器段錯誤頁面的源代碼 } StreamReader sr = new StreamReader(webResponse.GetResponseStream(), System.Text.Encoding.GetEncoding("UTF-8")); //GetResponseStream()方法獲取HTTP響應的數據流,並嘗試取得URL中所指定的網頁內容 //StreamReader類的Read方法依次讀取網頁源程式代碼每一行的內容,直至行尾(讀取的編碼格式:UTF8) rStr = sr.ReadToEnd(); sr.Close(); webResponse.Close(); //HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(rStr, System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }; //避免頁面出現<string></string>,只返回json欄位 //return result; return rStr; }View Code
訪問網址:http://localhost:58601/api/api/GetSendRequest?mo=001000012111
(http://localhost:58601/api/控制器名/方法名)
2、POST請求
[HttpPost] public string SendRequest(string param) { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); Encoding encoding = Encoding.UTF8; byte[] bs = Encoding.ASCII.GetBytes(param); string responseData = String.Empty; req.Method = "POST"; //application/x-www-form-urlencoded預設是a=1&b=2&c=3類型 //application/json預設參數是a:1&b:2&c:3類 req.ContentType = "application/x-www-form-urlencoded"; req.ContentLength = bs.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); } using (HttpWebResponse response = (HttpWebResponse)req.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding)) { responseData = reader.ReadToEnd().ToString(); } } // HttpResponseMessage result = new HttpResponseMessage { Content = new StringContent(responseData, System.Text.Encoding.GetEncoding("UTF-8"), "application/json") }; return responseData; }
訪問網址:http://localhost:58601/api/api/SendRequest?param=0&moid=1&partno=2&stationid=T
(http://localhost:58601/api/控制器名/方法名)