Search code examples
c#asp.net-coreasp.net-core-mvcasp.net-core-webapiasp.net-core-routing

How to add Web API controller to an existing ASP.NET Core MVC?


I created a project using the default ASP.NET Core MVC template. I would like to also create a RESTful API under /api/{Controller}. I added a new Web API controller (standard Web API controller class template) but I can't call it. I get an error saying that the page cannot be found. I tried adding a route in Startup.cs but it doesn't do anything:

app.UseMvc(routes =>
{
    routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
    routes.MapRoute(name: "api", template: "api/{controller=Admin}");
});

EDIT:

Like I said, it's all default templates. Here's the Web API Controller that I added:

[Route("api/[controller]")]
public class AdminController : Controller
{                
    // GET api/values/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
        return "value";
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody]string value)
    {
    }

    // PUT api/values/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
    }

    // DELETE api/values/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
    }
}

Solution

  • 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.