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 ?
Routing in ASP.NET Core Web API application is the process of mapping the incoming HTTP Request (URL) to a particular resource i.e. controller action method. For the Routing Concept in ASP.NET Core Web API, we generally set some URLs for each resource.
Routes direct incoming API requests to backend resources. Routes consist of two parts: an HTTP method and a resource path—for example, GET /pets . You can define specific HTTP methods for your route. Or, you can use the ANY method to match all methods that you haven't defined for a resource.
Right click your web project -> Select Properties -> Select the Debug tab on the left -> Then edit the 'Launch Url' field to set your own default launch url.
If you are familiar with ASP.NET MVC, Web API routing is very similar to MVC routing. The main difference is that Web API uses the HTTP verb, not the URI path, to select the action. You can also use MVC-style routing in Web API.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With