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

I created a project using the default ASP.NET Core MVC template. I would also like to create a RESTful API under /api/{Controller} . I added a new web API controller (standard API controller class template), but I can’t name it. I get a message that the page was not found. I tried adding a route to Startup.cs but did nothing:

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

EDIT:

As I said, all templates are by default. Here is 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) { } } 
+5
source share
3 answers

After upgrading to the latest version of ASP.NET Core, v2.0.1 (the one that VS2017 needs), the problem is resolved itself. I think it was a mistake or a flaw in the old version.

0
source

Two things.

First, when using routing based on conventions, more specific routes should appear before more general routes in order 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 already use attribute routing on the controller, so you should have been redirected to the controller, except for the fact that you do not have a route pattern on the controller that would accept /api/{Controller}

This will 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 } 
+2
source

Try entering the name "admin"

  app.UseMvc(routes => { routes.MapRoute( name: "Admin", template: "api/{controller=Admin}"); }); 
0
source

Source: https://habr.com/ru/post/1269493/


All Articles