当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net MVC下使用rest的方法

asp.net MVC下使用rest的方法

2017年09月22日  | 移动技术网IT编程  | 我要评论

瘸腿大兵,幽灵鬼屋历险记,花果山户外网

前言

最近做了下个mvc的项目,需要用到rest接口,与java写的应用程序通信,包括数据的接收和发送,那么我将用实用的角度来全面的讲解一下它的使用方法

一、创建rest服务

首先创建一个asp.net web应用程序(我这里用的是visual studio 2013,它已经内置了web api2)。

   

在出来的模板中选择empty(空项目),并勾选webapi。点击确定后,就创建了一个空的webapi服务。

   

此时只有一个空项目,还没有任何功能,在进行下一步之前,首先我们来看一下rest的基本操作模型,大致可以分为如下四种:

  • post — 创建资源
  • get — 检索资源
  • put — 更新资源
  • delete — 删除资源

非常经典的crud模型。在web api中实现这样一个的模型是非常简单的,直接使用向导建一个controller即可

 

  

如果用传统的向导,记得把向导后面的那个1给去掉:

默认的模板内容如下:

   public class valuescontroller : apicontroller
  {
    // get api/<controller>
    publicienumerable<string> get()
    {
      returnnewstring[] { "value1", "value2" };
    }

    // get api/<controller>/5
    publicstring get(int id)
    {
      return"value";
    }

    // post api/<controller>
    publicvoid post([frombody]string value)
    {
    }

    // put api/<controller>/5
    publicvoid put(int id, [frombody]string value)
    {
    }

    // delete api/<controller>/5
    publicvoid delete(int id)
    {
    }
  }

这其实已经帮我们实现了一个最基本的服务了,这样别人就可以访问我们的服务中的方法

二、调用其它应用程序的rest服务

1、restclient类

为了便于使用,我们需要封装客房端的rest类,话不多说,我们直接上这个类的代码:

using system;
using system.collections.generic;
using system.io;
using system.linq;
using system.net;
using system.text;
using system.web;

namespace oildigital.a2_a27.web
{
  public class restclient
  {
    public string endpoint { get; set; }  //请求的url地址 
    public httpverb method { get; set; }  //请求的方法 
    public string contenttype { get; set; } //格式类型:我用的是application/json,text/xml具体使用什么,看需求吧 
    public string postdata { get; set; }  //传送的数据,当然了我使用的是json字符串 

    public restclient()
    {
      endpoint = "";
      method = httpverb.get;
      contenttype = "application/x-www-form-urlencoded";
      postdata = "";
    }
    public restclient(string endpoint)
    {
      endpoint = endpoint;
      method = httpverb.get;
      contenttype = "application/json";
      postdata = "";
    }
    public restclient(string endpoint, httpverb method)
    {
      endpoint = endpoint;
      method = method;
      contenttype = "application/json";
      postdata = "";
    }

    public restclient(string endpoint, httpverb method, string postdata)
    {
      endpoint = endpoint;
      method = method;
      contenttype = "application/json";
      postdata = postdata;
    }
    public restclient(string endpoint, httpverb method, string postdata, string contenttype)
    {
      endpoint = endpoint;
      method = method;
      contenttype = contenttype;
      postdata = postdata;
    }

    public string makerequest()
    {
      return makerequest("");
    }

    public string makerequest(string parameters)
    {

      var request = (httpwebrequest)webrequest.create(endpoint + parameters);
      request.method = method.tostring();
      request.contenttype = contenttype;
      
      if (!string.isnullorempty(postdata) && method == httpverb.post)//如果传送的数据不为空,并且方法是post 
      {
        var encoding = new utf8encoding();   
        var bytes = encoding.getencoding("iso-8859-1").getbytes(postdata);//编码方式按自己需求进行更改,我在项目中使用的是utf-8 
        request.contentlength = bytes.length;

        using (var writestream = request.getrequeststream())
        {
          writestream.write(bytes, 0, bytes.length);
        }
      }

      if (!string.isnullorempty(postdata) && method == httpverb.put)//如果传送的数据不为空,并且方法是put 
      {
        var encoding = new utf8encoding();
        var bytes = encoding.getencoding("iso-8859-1").getbytes(postdata);//编码方式按自己需求进行更改,我在项目中使用的是utf-8 
        request.contentlength = bytes.length;

        using (var writestream = request.getrequeststream())
        {
          writestream.write(bytes, 0, bytes.length);
        }

      }
      using (var response = (httpwebresponse)request.getresponse())
      {
        var responsevalue = string.empty;

        if (response.statuscode != httpstatuscode.ok)
        {
          var message = string.format("request failed. received http {0}", response.statuscode);
          throw new applicationexception(message);
        }

        // grab the response 
        using (var responsestream = response.getresponsestream())
        {
          if (responsestream != null)
            using (var reader = new streamreader(responsestream))
            {
              responsevalue = reader.readtoend();
            }
        }

        return responsevalue;
      }
    }

  }
  public enum httpverb
  {
    get,      //method 常用的就这几样,当然你也可以添加其他的  get:获取  post:修改  put:写入  delete:删除 
    post,
    put,
    delete
  }


}

2、restclient类使用

有了这个类后我们就很方便的去调用别人的rest服务了,使用方法如下:

①,基本的调用:

var client = new restclient();
string endpoint = @"http:\\myrestservice.com\api\";
var client = new restclient(endpoint);
var json = client.makerequest(); 

②,如果你想带入参数

var json = client.makerequest("?param=0");

③,使用最多的方式

var client = new restclient();
client.endpoint = @"http:\\myrestservice.com\api\"; ;
client.contenttype = "application/json";
client.method = httpverb.post;
client.postdata = "{postdata: value}";
var json = client.makerequest();

三、我自己项目中的使用

1、首先我测试了一下,我调用我自己的rest服务的带参的get方法,当然我这里传的参数直接写在url的后面在,参数形式是string,所以接收的get方法的形参也要改成string,这样你就

可以接收到传过去的参数了。当然别人应用程序也是可以调的。只要把url给他就行了。

/// <summary>
    /// 从接口中获取当前用户所有信息
    /// </summary>
    /// <param name="userid">用户id</param>
    /// <returns>json对象</returns>
    public string getcurrentuserinfo()
    {
      string userid = getcurrentuserid();
      string endpoint = "http://localhost:100/api/restservice/"+userid;
      var client = new restclient(endpoint);
      var userinfo = client.makerequest();
      return userinfo;
    }

2、接下来,我要开始试用java写的应用程序下的rest服务了,我通过我传过去的用户id获取到了用户的所有信息,当然我在项目中使用了缓存技术,还将返回回来的json字符串转换成了json对象,以便我后面好用linq对其进行操作,关于linq to json 可以参考我的linq专题相关文章 ,我在项目中的代码是酱子的:

/// <summary>
    /// 从接口中获取用户所有信息
    /// </summary>
    /// <param name="userid">用户id</param>
    /// <returns></returns>
    public static jobject cacheuser()
    {

      try
      {
        string currentuser = getcurrentuserid();
        if (httpruntime.cache.get("user$" + getcurrentuserid()) == null)
        {
          string endpoint = "http://66.66.66.666:6666/dasbase/restservices/datacollectionservice/getuserpermissions";
          string postdata = "jsondata={\"usercode\": \"kfry\",\"systemid\": \"1e1a7ac94bfc41d4bebed8942eb69689\"}";
          var client = new restclient(endpoint, httpverb.post, postdata, "application/x-www-form-urlencoded");
          var u = client.makerequest();
          jobject userinfo = jobject.parse(u);
          //插入缓存
          httpruntime.cache.insert("user$" + currentuser, userinfo, null, system.datetime.utcnow.addminutes(30), timespan.zero);
        }
        return (jobject)httpruntime.cache.get("user$" + getcurrentuserid());
      }
      catch (exception ex)
      {

        throw new applicationexception("获取用户信息出错:"+ex.message);
      }
    }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网