I have started learning webApi in Mvc5.
I tried my first project but unfortunately it doesn't work and I can't understand why.
i have done these steps:
1- At first I created a database named Person in sql server
2- Then I added a table named Person with these fields: Id as primary key and FullName
3- I made an Empty MVC project is vs 2013
4- I added my EF model and rebuilt the project
5- I created a new Folder named api
6- I added a controller (Web Api 2 with Actions, using Entity Framework):
7- I added these lines to Global.asax
using System.Web.Http;
using System.Web.Routing;
8 - And here is my Application-start:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
But When I run the application and I enter http://localhost:XXXX/api/people
into the url browser can't find the resource.
Can anyone please help me?
Thanks in advance
And here is PeopleController:
public class PeopleController : ApiController
{
private PersonEntities db = new PersonEntities();
// GET api/People
public IQueryable<Person> GetPeople()
{
return db.People;
}
// GET api/People/5
[ResponseType(typeof(Person))]
public IHttpActionResult GetPerson(int id)
{
Person person = db.People.Find(id);
if (person == null)
{
return NotFound();
}
return Ok(person);
}
// PUT api/People/5
public IHttpActionResult PutPerson(int id, Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != person.Id)
{
return BadRequest();
}
db.Entry(person).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!PersonExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
// POST api/People
[ResponseType(typeof(Person))]
public IHttpActionResult PostPerson(Person person)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
db.People.Add(person);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = person.Id }, person);
}
// DELETE api/People/5
[ResponseType(typeof(Person))]
public IHttpActionResult DeletePerson(int id)
{
Person person = db.People.Find(id);
if (person == null)
{
return NotFound();
}
db.People.Remove(person);
db.SaveChanges();
return Ok(person);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool PersonExists(int id)
{
return db.People.Count(e => e.Id == id) > 0;
}
}