Roadmap › AngularJS (1.x) — Legacy › Module: Fundamentals
Lessons in this course (13)
5. Connecting AngularJS to SQL Server (through ASP.NET Web API)
Intermediate★ Must knowLesson 5 of 13
The classic stack: AngularJS → ASP.NET Web API 2 (or MVC 5 JSON actions) → ADO.NET/EF6 → SQL Server, often hosted together in one IIS site.
csharp
// ASP.NET Web API 2 (.NET Framework) — Controllers/ProductsController.cs
public class ProductsController : ApiController
{
private readonly string _cs = ConfigurationManager.ConnectionStrings["Shop"].ConnectionString; // Web.config
[HttpGet, Route("api/products")]
public IHttpActionResult Get()
{
var list = new List<object>();
using (var conn = new SqlConnection(_cs))
using (var cmd = new SqlCommand("SELECT Id, Name, Price FROM dbo.Products ORDER BY Name", conn))
{
conn.Open();
using (var r = cmd.ExecuteReader())
while (r.Read()) list.Add(new { id = r.GetInt32(0), name = r.GetString(1), price = r.GetDecimal(2) });
}
return Ok(list);
}
}xml
<!-- Web.config -->
<connectionStrings>
<add name="Shop" connectionString="Data Source=.;Initial Catalog=Shop;Integrated Security=True" providerName="System.Data.SqlClient" />
</connectionStrings>js
// app/products/products.service.js
angular.module('shopApp').factory('productService', ['$http', 'API_URL', function ($http, API_URL) {
return {
getAll: function () { return $http.get(API_URL + '/products').then(function (res) { return res.data; }); },
create: function (p) { return $http.post(API_URL + '/products', p).then(function (res) { return res.data; }); }
};
}]);Same origin (AngularJS files served by the same IIS site as the API) means no CORS configuration is needed; otherwise enable CORS in Web API (config.EnableCors()). When migrating, the Web API backend can usually be kept while the AngularJS front end is rewritten in Angular or React.