webapi创建及POST、GET访问

 

一、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;
 try
            {   
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();    }    }
   catch (Exception e)
            {
              
            }
// 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/控制器名/方法名)

posted @ 2020-03-10 15:22  越吃越瘦  阅读(1352)  评论(0编辑  收藏  举报