Reputation: 4175
I am trying to implement a generic API Controller to be used for all models.
public class DefaultController<T> : ApiController
{
// GET: api/Default
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Default/5
public string Get(int id)
{
return "value";
}
}
When I call localhost:xxxxxx/api/Default. It throws error
No type was found that matches the controller named 'Default'.
Can someone please guide me the correct way to implement.
Also, How do I specify type while calling API?
Thanks.
Upvotes: 0
Views: 2107
Reputation: 3230
Try inherit from a generic base controller instead.
public class MyBaseController<T> : ApiController
{
// GET: api/Default
public IEnumerable<T> Get()
{
return callGenericMethod<T>();
}
}
And now create as many controller as you want:
public class DefaultController : MyBaseController<MySpecificType>
{
//add extra specific methods here or depend on the inherited ones only.
}
And calling the controller will be the same as calling none generic one:
yourApiPath/Default/Get
Upvotes: 0
Reputation: 336
If this is your Generic API Controller (Base Controller)
:
[Route("api/[controller]")]
public class DefaultController<T> : ApiController
{
// GET: api/{ControllerName}
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "first", "second" };
}
// GET: api/{ControllerName}/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
}
You can use the base controller for Posts
:
public class PostsController : DefaultController<Post> {}
Or use for others such as Comments
:
public class CommentsController : DefaultController<Comment> {}
And you can call controller actions localhost:xxxx/api/posts
, localhost:xxxx/api/posts/5
, localhost:xxxx/api/comments
, localhost:xxxx/api/comments/12
Upvotes: 2