ASP.NET WebAPI连接数据库的方法
这篇文章主要为大家详细介绍了ASP.NET WebAPI连接数据库的方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
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字符串格式返回:
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) { } } } |
运行项目:
获得返回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 | { "Table" : [ { "UserID" : 1, "UserName" : "admin" , "DisplayName" : "admin1" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Email" : "289602025@qq.com" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null }, { "UserID" : 2, "UserName" : "admin1" , "DisplayName" : "admin1" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Email" : "289602025@qq.com" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null }, { "UserID" : 3, "UserName" : "admin2" , "DisplayName" : "admin2" , "Password" : "jZae727K08KaOmKSgOaGzww/XVqGr/PKEgIMkjrcbJI=" , "Email" : "289602025@qq.com" , "Status" : 0, "RegistrationTime" : "2017/6/1" , "LoginTime" : null , "LoginIP" : null } ] } |
以上就是本文的全部内容,希望对大家的学习有所帮助