Skip to content

Instantly share code, notes, and snippets.

@LinZap
Created March 15, 2018 10:00
Show Gist options
  • Save LinZap/dd678497b8bf689f594c27d30028b721 to your computer and use it in GitHub Desktop.
Save LinZap/dd678497b8bf689f594c27d30028b721 to your computer and use it in GitHub Desktop.
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;
}
}
@yamasol
Copy link

yamasol commented Mar 16, 2018

resp.Content.Headers.ContentType.CharSet = "utf-8";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment