我有这个API项目来了解员工的详细信息。如何在Home控制器中获取类似于“ http://localhost:53037/api/employee/4”的API URL,并将该URL保存到数据库中?
员工控制者:
public class EmployeeController : ApiController
{
public IEnumerable<Employee> Get()
{
using(EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.ToList();
}
}
public Employee Get(int id)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.FirstOrDefault(e => e.ID == id);
}
}
public void Post([FromBody] Employee employee)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
entities.Employees.Add(employee);
entities.SaveChanges();
}
}
}
家庭控制器:
public class HomeController : Controller
{
private readonly MyDBEntities _db = new MyDBEntities();
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
答案 0 :(得分:0)
我认为关键是使用适当的属性
[HttpGet]
[Route("/api/employee/{id}/")]
public Employee Get([FromRoute]int id)
{
using (EmployeeDBEntities entities = new EmployeeDBEntities())
{
return entities.Employees.FirstOrDefault(e => e.ID == id);
}
}
编辑:不确定我是否正确理解了这个问题,但是如果您尝试通过id从数据库中获取一名员工,这就是方法。与员工有关的所有事情都应通过EmployeeController进行。