【发布时间】:2017-06-03 10:55:16
【问题描述】:
我是构造函数的新手。请解释为什么它给我以下错误:
"An error occurred when trying to create a controller of type 'HomeController'. Make sure that the controller has a parameterless public constructor.
这里我有 1 个接口 (IRepo) 1 个类文件 (Repo) IRepo.cs
public interface IRepo
{
IEnumerable<Employee> GetEmployee();
IQueryable<Employee> GetEmployee(int id);
}
Repo.cs
Ctxdb _db = null;
public Repo(Ctxdb db)
{
this._db = db;
}
public IEnumerable<Employee> GetEmployee()
{
//
}
HomeController.cs
IRepo _ObjRepo = null;
public HomeController(Repo ObjRepo)
{
_ObjRepo = ObjRepo;
}
[Route("GetEmp")]
[HttpGet]
public IHttpActionResult GetDat()
{
var x = _ObjRepo.GetEmployee();
if (x != null)
return Content(HttpStatusCode.OK, x);
else
return Content(HttpStatusCode.BadRequest,"Not Implemented");
}
【问题讨论】:
-
只在你的控制器中有一个无参数的构造函数。
-
但是我很困惑,你能不能给我任何提示
-
这很清楚:您需要创建一个不带参数的公共构造函数...示例:
public HomeController()此外,有很多问题的答案都在谈论这个问题。请参考这些帖子 -
是的,我创建了 public HomeController(Repo ObjRepo) { _ObjRepo = ObjRepo; } 以这种方式,但我怎么能调用它
标签: c# asp.net-web-api