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) { } } }
运行项目:
获得返回Json字符串数据:
{ "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 } ] }