最近做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);}}}
簡單寫到這里!!