Created
March 15, 2018 10:00
-
-
Save LinZap/dd678497b8bf689f594c27d30028b721 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class EntityController : ApiController | |
{ | |
[HttpGet] | |
public HttpResponseMessage getEntity(int eid) { | |
// 開啟連線 | |
SqlConnection conn = new SqlConnection("Server=192.168.1.190;Database=TestFpage;User ID=apitester;Password=Iq123456"); | |
conn.Open(); | |
// SQL 指令 | |
SqlCommand cmd = new SqlCommand(); | |
cmd.Connection = conn; | |
// 指定 SQL 語法 | |
cmd.CommandText = "select * from entity where eid="+ eid; | |
cmd.CommandType = CommandType.Text; | |
// 建立讀取物件 | |
SqlDataReader r = cmd.ExecuteReader(); | |
// 取出每一筆資料,並繫結到 Model | |
List<ModelEntity> list = new List<ModelEntity>(); | |
while (r.Read()) | |
{ | |
ModelEntity entity = new ModelEntity(); | |
entity.eid = r.GetInt16(0); | |
entity.cname = r.GetString(1); | |
entity.ename = r.GetString(2); | |
entity.borel = r.GetInt32(3); | |
list.Add(entity); | |
} | |
// 關閉連線 | |
r.Close(); | |
conn.Close(); | |
// 序列化並輸出 | |
string json = JsonConvert.SerializeObject(list); | |
var resp = new HttpResponseMessage() | |
{ | |
Content = new StringContent(json) | |
}; | |
resp.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); | |
return resp; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
resp.Content.Headers.ContentType.CharSet = "utf-8";