標籤:targe text status namespace 擷取 data- min size 實現
ASP.NET Web API 是一種架構,用於輕鬆構建可以訪問多種用戶端(包括瀏覽器和行動裝置)的 HTTP 服務。 ASP.NET Web API 是一種用於在 .NET Framework 上構建 RESTful 應用程式的理想平台。 本文主要實現ASP.NET WebAPI 串連資料庫擷取資料,並以Json字串格式返回。 1.建立ASP.NET Web Application(.NET Framework)項目; 2.選擇Web API; 3.建立新項目完成; 在ValuesController.cs中修改Get方法並串連SQLServer資料庫擷取資料,以Json字串格式返回:
using System;using System.Collections.Generic;using System.Data;using System.Data.SqlClient;using System.Web.Http;using Newtonsoft.Json;namespace WebApplication1.Controllers{ public class ValuesController : ApiController { // GET api/values public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 public string Get(int id) { try { SqlConnection sqlConnection = new SqlConnection( "Data Source=127.0.0.1;Initial Catalog=GaryWeb;Integrated Security=True;User Id=sa;Password=123456"); sqlConnection.Open(); string sql = "select * from Users"; DataSet dataSet = new DataSet(); SqlDataAdapter sqlDataAdapter = new SqlDataAdapter(sql, sqlConnection); sqlDataAdapter.Fill(dataSet); return JsonConvert.SerializeObject(dataSet); } catch (Exception ex) { return ex.ToString(); } } // POST api/values public void Post([FromBody]string value) { } // PUT api/values/5 public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 public void Delete(int id) { } }}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
運行項目: 獲得返回Json字串資料:
{ "Table": [ { "UserID": 1, "UserName": "admin", "DisplayName": "admin1", "Password": "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=", "Email": "[email protected]", "Status": 0, "RegistrationTime": "2017/6/1", "LoginTime": null, "LoginIP": null }, { "UserID": 2, "UserName": "admin1", "DisplayName": "admin1", "Password": "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=", "Email": "[email protected]", "Status": 0, "RegistrationTime": "2017/6/1", "LoginTime": null, "LoginIP": null }, { "UserID": 3, "UserName": "admin2", "DisplayName": "admin2", "Password": "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=", "Email": "[email protected]", "Status": 0, "RegistrationTime": "2017/6/1", "LoginTime": null, "LoginIP": null } ]}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
ASP.NET WebAPI 串連資料庫