Skip to content

Instantly share code, notes, and snippets.

@LinZap
Created March 15, 2018 10:07
Show Gist options
  • Save LinZap/d940a51077ae91556439ccb6a1e1a1ef to your computer and use it in GitHub Desktop.
Save LinZap/d940a51077ae91556439ccb6a1e1a1ef 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;
cmd.Parameters.AddWithValue("@eid", eid);
// 建立讀取物件
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

如何防範:
1.使用 Regular expression 驗證過濾輸入值與參數中惡意代碼,將輸入值中的單引號置換為雙引號。
2.限制輸入字元格式並檢查輸入長度。
3.資料庫設定使用者帳號權限,限制某些管道使用者無法作資料庫存取。

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