最近做CS项目,一直在使用TCP+Socket 做数据传输,不太爽,砸门可是多年BS的开发,这样开发接口出去比较费劲,但是又不想用asp.net mvc webapi,要按照IIS,有些工控机的系统环境也是很尴尬的,那么也可以用wcf啊,不用依赖IIS,比较麻烦。所以还是用了Nancy!
1 老规矩,Nuget下载!
2 简单画个页面
3 上代码 (NancyModule) 注意Post方法的From参数获取和Body参数获取,代码中均有给到
/// <summary>/// 使用NancyModule来定义路由/// </summary>public class CustomNancyModule : NancyModule{//private static readonly XDeclaration _defaultDeclaration = new XDeclaration("1.0", null, null);public CustomNancyModule(){Get("/", x => { return "Hello World!"; }); // 单斜杆位根节点,这里和mvc 中的 路由是一样的Get("/greet/{name}", x =>{return "Hello " + x.name;});Get("/GetJsonOBJ", x =>{return Response.AsJson(new { name = "张三" });});Get("/GetMyText", x =>{return Response.AsText("我是文本", System.Text.Encoding.UTF8);});Get("/GetRequsetInfo", x =>{List<Para> list = new List<Para>();Para para = new Para();para.A = Request.Query["A"];para.B = Request.Query["B"];list.Add(para);return Response.AsJson(para); //会自动转JSON });Post("/data", x =>{// 获取 POST 的 JSON 字符串if (this.Request.Body.CanRead){this.Request.Body.ReadByte();}var jsonStr = GetStreamStr(this.Request.Body);//string name = Request.Form["name"];//string age = Request.Form["age"];string readString = jsonStr;Para para = new Para();para.A = this.Request.Form["A"];para.B = this.Request.Form["B"];return Response.AsJson(para); //会自动转JSON});}public string GetStreamStr(Stream stream){string readString = "";if (stream.CanRead){stream.Position = 0;byte[] readBuffer = new byte[stream.Length];int count = stream.Read(readBuffer, 0, readBuffer.Length);//首先通过流读出的readBuffer的数据求出从相应Char的数量int charCount = Encoding.Default.GetCharCount(readBuffer, 0, count);//通过该Char的数量 设定一个新的readCharArray数组char[] readCharArray = new char[charCount];//Encoding 类的强悍之处就是不仅包含加密的方法,甚至将解密者都能创建出来(GetDecoder()),//解密者便会将readCharArray填充(通过GetChars方法,把readBuffer 逐个转化将byte转化成char,并且按一致顺序填充到readCharArray中)Encoding.Default.GetDecoder().GetChars(readBuffer, 0, count, readCharArray, 0);for (int i = 0; i < readCharArray.Length; i++){readString += readCharArray[i];}stream.Close();}return readString;}public class JsonReslut<T> where T : class{public int result { get; set; }public T Obj { get; set; }}public class Para{public string A { get; set; }public string B { get; set; }}}
2 页面代码
public partial class Nancy_Form : Form{public Nancy_Form(){InitializeComponent();}private NancyHost host;//开始private void button1_Click(object sender, EventArgs e){try{if (host != null){richTextBox1.AppendText("已经启动 \r\n");return;}//Nancy Self Host 必须加上 AutomaticUrlReservationCreation, 否则 host.Start()会报异常HostConfiguration hostConfigs = new HostConfiguration(){UrlReservations = new UrlReservations() { CreateAutomatically = true }}; // 创建 NancyHost 实例host = new NancyHost(new Uri("http://localhost:8082"), new DefaultNancyBootstrapper(), hostConfigs); // 启动 NancyHosthost.Start();richTextBox1.AppendText("Running on http://localhost:8082 \r\n");}catch (Exception ex){richTextBox1.AppendText("站点启动失败:" + ex.Message);}}//关闭private void button2_Click(object sender, EventArgs e){try{if (host == null){richTextBox1.AppendText("站点已经停止 \r\n");return;}// 停止 NancyHosthost.Stop();host = null;richTextBox1.AppendText("站点已经停止 \r\n");}catch (Exception ex){richTextBox1.AppendText("站点停止失败," + ex.Message);}}}
简单写到这里!!