發表文章

目前顯示的是有「WebAPI」標籤的文章

C# WebAPI 傳入JSON, 回傳資料格式為文字 [GET]

C# WebAPI 傳入JSON, 回傳資料格式為文字 [GET] API Code public IHttpActionResult Get(string param1, string param2) { string result = ""; try { // 檢查參數是否合法 if (string.IsNullOrEmpty(param1)) { throw new Exception("param1 參數不能為空。"); } if (string.IsNullOrEmpty(param2)) { throw new Exception("param2 參數不能為空。"); } // 進行資料處理邏輯,這裡假設將兩個參數結合成一個字串 result = $"OK,[GET]result is {param1}-{param2}"; // 返回結果 return Ok(result); } catch (Exception exp) { result = $"NG,{exp.Message}"; } return Ok(result); ; } 呼叫時在網址後加?param1=&param2= 回傳結果如下, 失敗: "NG,參數不可為空" 成功: "OK,result is value1-value2"  

C# WebAPI 傳入JSON, 回傳資料格式為文字 [POST]

C# WebAPI 傳入JSON, 回傳資料格式為文字 [POST] API Code public IHttpActionResult Post([FromBody] Api_TESTPData parameters) { string result = ""; try { if (parameters == null) { throw new Exception("參數不可為空"); } /* 資料處理邏輯 */ result = $"OK,result is {parameters.Param1}-{parameters.Param2}"; } catch (Exception exp) { result = $"NG,{exp.Message}"; } return Ok(result); ; } Paramter Code public class Api_TESTPData { public string Param1 { get; set; } public string Param2 { get; set; } } 回傳結果如下, 失敗: "NG,參數不可為空" 成功: "OK,result is value1-value2"  

C# 桌面程式也能當作WebAPI服務器

圖片
有時希望桌面程式(Winform , Console...)也能接受別的程式呼叫觸發對應動作, 可以使用這個方法。 參考資料: https://blog.darkthread.net/blog/self-host-web-api/ STEP-01 在桌面程式程式(這裡使用Console), 透過Nuget安裝[Microsoft.AspNet.WebApi.SelfHost]。(輸入self host就可以找到) STEP-02 新增下面API服務CODE static void Main(string[] args) { //指定聆聽的URL var config = new HttpSelfHostConfiguration("http://localhost:22222"); //注意: 在Vista, Win7/8,預設需以管理者權限執行才能繫結到指定URL,否則要透過以下指令授權 //開放授權 netsh http add urlacl url=http://+:32767/ user=machine\username //移除權限 netsh http delete urlacl url=http://+:32767/ //設定路由 config.Routes.MapHttpRoute("API", "{controller}/{action}/{id}", new { id = RouteParameter.Optional }); //設定Self-Host Server,由於會使用到網路資源,用using確保會Dispose()加以釋放 using (var httpServer = new HttpSelfHostServer(config)) { //OpenAsync()屬非同步呼叫,加上Wait()...