使用JSON比起傳統的Web Service的XML實在好用太多,不用搞WSDL,還要處理Parser的問題,真的很麻煩。
最終WebApi一定會變成網頁傳遞資料的主流,NET MVC架構裡的ApiController實在很犀利。以下範例可以在ApiController直接產生json檔案輸出,讓對方讀取,直接用Dictionary就變成JSON資料,這個讚。
[HttpGet]
public Dictionary<string, string> GetLoginToken()
{
var result = new Dictionary<string, string>();
try
{
result.Add("token", DoSomething());
result.Add("ErrMsg", "");
}
catch (Exception e)
{
result.Add("token", "");
result.Add("ErrMsg", e.Message);
}
return result;
}
既然 Dictionary 可以轉JSON,那麼JSON可以轉為 Dictionary 嗎?當然可以喔,如下:
// 設定GET網址與表頭
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("https://localhost:44366/api/login/Test?token=abc");
request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
// 接收回傳的資料
string responseStr = "";
using (System.Net.WebResponse response = request.GetResponse())
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
{
responseStr = sr.ReadToEnd();
}
}
// 印出接收的資料
//Response.Write(responseStr);
//Response.End();
// 不印出資料但把接收的JSON資料轉出來用
var payload = JsonConvert.DeserializeObject<Dictionary<string, string>>(responseStr);
Response.Write(payload["VerifyPass"]);
Response.End();
PS:以上轉換記得要NuGet套件 Newtonsoft.Json ( Json.NET )才可以用喔。