Routes in ASP.net Core API
70,294
Solution 1
Try this. You can put a common route prefix on the controller.
[Route("api/[controller]")]
public class BXLogsController : Controller {
//GET api/BXlogs/id/blah
[HttpGet("ID/{id}", Name = "GetL")]
public IActionResult GetById(string id) { ... }
//GET api/BXlogs/api/blahapi
[HttpGet("API/{apiname}", Name = "GetLAPI")]
public IActionResult GetByAPI(string apiname) { ... }
}
read up on attribute routing here Routing to Controller Actions
Solution 2
In case if you're planning to have a custom action name similar to web API's.
[Route("api/[controller]")]
public class BXLogsController : Controller {
//GET api/BXlogs/blahapi
[HttpGet("{apiname}", Name = "GetLAPI")]
public IActionResult GetByAPI(string apiname) { ... }
}
a little extended to @nkosi
So you'll be calling as
GET: https://localhost:44302/api/BXLogs/GetLAPI
Related videos on Youtube
Author by
Gobelet
Updated on July 09, 2022Comments
-
Gobelet almost 2 years
I read lot of topic about routes for API in Asp.net core but I cannot make it work.
First, this is my controller :
Public class BXLogsController : Controller { //[HttpGet("api/[controller]/ID/{id}", Name = "GetL")] public IActionResult GetById(string id) { if (id.Trim() == "") return BadRequest(); else { Logs l = AccessBase.AccBase.GetLog(id); return Json(l); } } //[HttpGet("api/[controller]/API/{apiname}", Name = "GetLAPI")] public IActionResult GetByAPI(string apiname) { if (apiname.Trim() == "") return BadRequest(); else { List<Logs> lstLogs = AccessBase.AccBase.GetLogsApi(apiname); return Json(lstLogs); } } }
I tried to use the
HttpGetAttribute
with the path (refer to comment) but that doesn't work.So I want to use
MapRoute
approach but that doesn't work also.app.UseMvc(routes => { routes.MapRoute( name: "LogsId", template: "api/[controller]/ID/{id}", defaults: new { controller = "BXLogs", action = "GetById" }); routes.MapRoute( name: "LogsAPI", template: "api/[controller]/API/{apiname}", defaults: new { controller = "BXLogs", action = "GetByAPI" }); });
I must have forgotten something but I see nothing.
Anyone can help me ?
-
Fabricio Koch over 7 yearsMake sure there's no duplicated routes.
-
-
paulroho over 7 yearsOr this tutorial: https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-web-api