MVC中 webapi的使用 和 在其他网站中如何来调用(MVC)  

1、webapi的路由规则注册在App_Start\WebApiConfig.cs文件中

 2、webapi控制器继承父类 apiController     

3、调用webapi的方式:   get请求http://localhost/api/home/1 则默认请求 Home控制器下的Get方法将1作为get()方法的参数   Post请求http://localhost/api/home/1 则默认请求 Home控制器下的Post方法将1作为Post()方法的参数  

4、将webapi默认的返回格式设置成json格式写法    public static class WebApiConfig   {         public static void Register(HttpConfiguration config)         {             //将webapi中的XmlFormatter 移除,默认就是以JsonFormatter作为其传输格式             config.Formatters.Remove(config.Formatters.XmlFormatter);   }   

5、在另外一个网站请求使用httpwebrequest 请求webapi示例:    //模拟浏览器请求http://localhost:55749/api/values/GetPig 传入指定的id参数值          string requestUrl = "http://localhost:15405/infos.ashx?id=" + txtid.Text;  

 //1.0 实例化web请求对象的实例   WebRequest request = WebRequest.Create(requestUrl);   //2.0 设置其请求方式为get请求   request.Method = "get";   //3.0 获取服务器响应回来的响应报文对象   WebResponse response = request.GetResponse();   System.IO.Stream str = response.GetResponseStream();

  //将流转换成字符串   string responsebody = "";   using (System.IO.StreamReader srd = new System.IO.StreamReader(str))   {    //将响应报文体中的数据转换成字符串    responsebody=srd.ReadToEnd();   }

  Response.Write(responsebody);

posted on 2014-11-08 08:01  余昭(Ray)  阅读(418)  评论(0编辑  收藏  举报