ASP.NET Web API 是一種框架,用于輕松構(gòu)建可以訪問多種客戶端(包括瀏覽器和移動(dòng)設(shè)備)的 HTTP 服務(wù)。 ASP.NET Web API 是一種用于在 .NET Framework 上構(gòu)建 RESTful 應(yīng)用程序的理想平臺(tái)。
本文主要實(shí)現(xiàn)ASP.NET WebAPI 連接數(shù)據(jù)庫獲取數(shù)據(jù),并以Json字符串格式返回。
1.創(chuàng)建ASP.NET Web Application(.NET Framework)項(xiàng)目;
2.選擇Web API;
3.創(chuàng)建新項(xiàng)目完成;
在ValuesController.cs中修改Get方法并連接SQLServer數(shù)據(jù)庫獲取數(shù)據(jù),以Json字符串格式返回:
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
|
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) { } } } |
運(yùn)行項(xiàng)目:
獲得返回Json字符串?dāng)?shù)據(jù):
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
|
{ "Table" : [ { "UserID" : 1, "UserName" : "admin" , "DisplayName" : "admin1" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null }, { "UserID" : 2, "UserName" : "admin1" , "DisplayName" : "admin1" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null }, { "UserID" : 3, "UserName" : "admin2" , "DisplayName" : "admin2" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null } ] } |
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/Gary_888/article/details/72867741