How to add Web API controller to an existing ASP.NET Core MVC?
Two things.
First, when using convention-based routing, more specific routes should come before more generic routes to avoid route conflicts.
app.UseMvc(routes =>
{
routes.MapRoute(name: "api", template: "api/{controller=Admin}");
routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
});
Secondly, you are already using attribute routeing on the controller so should have been able to route to the controller except for the fact that you do not have a route template on the controller that would accept /api/{Controller}
That would require a default route
[Route("api/[controller]")]
public class AdminController : Controller {
[HttpGet("")] //Matches GET api/admin <-- Would also work with [HttpGet]
public IActionResult Get() {
return Ok();
}
[HttpGet("{id}")] //Matches GET api/admin/5
public IActionResult Get(int id) {
return Ok("value");
}
//...other code removed for brevity
}
If someone still have problem in adding webapi to .net core MVC, just inserting [ApiController]
and [Route("api/[controller]")]
attributes before class solves the problem:
[Route("api/[controller]")]
[ApiController]
public class ListController
{ ... }
I didn't added a route mapping in Startup.cs
and still working well. The version of .net that I am using is 2.1.402
After updating to the latest version of ASP.NET Core, v2.0.1 (the one that needs VS2017), the problem resolved itself. I think it was probably a bug or shortcoming in the old version.