zoukankan      html  css  js  c++  java
  • mvc中的webapi

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

    1、webapi的路由规则注册在App_StartWebApiConfig.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);

  • 相关阅读:
    HttpWebRequest后台读取网页类
    MD5加密方法
    Base64封装类
    3DES封装类
    C#操作XML类
    XML_Qt_资料
    XML_CPP_资料
    h.264_javascript_资料
    ffmpeg_资料_01
    QWebEngineView_简单例子_01
  • 原文地址:https://www.cnblogs.com/wtujvk/p/4082680.html
Copyright © 2011-2022 走看看