Using my entities I created a new context that I can use to query my database. Here is my controller class.
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace SLRiaWebAPiDemo.Web
{
public classGroupsController : ApiController
{
MRM_LatestEntities _context = new MRM_LatestEntities();
//List<Group> groups = new List<Group>();
// GET api/<controller>
public IEnumerable<Group> GetAllGroups()
{
return _context.Groups;
//return new string[] { "value1", "value2" };
}
// GET api/<controller>/5
public Group GetGroupById(int id)
{
return _context.Groups.Where(x => x.Id == id).FirstOrDefault();
//return "value";
}
// POST api/<controller>
public void Post([FromBody]string value)
{
}
// PUT api/<controller>/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Finally we need to tell our app to route to this controller when the URL is looking for it. In order to do this we need to add the controller mappings in the configurations of our app.
Add a new class file & name it "WebApiConfig.cs". This class will have the configuration code we need.
using System.Web.Http;
namespace SLRiaWebAPiDemo.Web
{
public classWebApiConfig
{
public staticvoid Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name:"DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults:new { id = RouteParameter.Optional }
//defaults: new { controller = "Test", action = "Get", id = "" }
);
}
}
}
Open this file & write the following within App_Start:
using System;
using System.Web.Http;
namespace SLRiaWebAPiDemo.Web
{
public classGlobal : System.Web.HttpApplication
{
protected void Application_Start(object sender,EventArgs e)
{
WebApiConfig.Register(GlobalConfiguration.Configuration);
}
}
}
That's all we need. Put a breakpoint at the GetAllGroups() method in WebApi Controller & hit F5.
When the app is up & running for example http://localhost:1778/Default.aspx change it to http://localhost:1778/api/groups/ Hit enter and you will see that the breakpoint is hit. Continue debugging & you will see the JSON data in the browser.