[英]Routes in ASP.net Core API
I read lot of topic about routes for API in Asp.net core but I cannot make it work.我在 Asp.net 核心中阅读了很多关于 API 路由的主题,但我无法让它工作。
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.我尝试将
HttpGetAttribute
与路径一起使用(请参阅注释),但这不起作用。
So I want to use MapRoute
approach but that doesn't work also.所以我想使用
MapRoute
方法,但这也不起作用。
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 ?任何人都可以帮助我吗?
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在此处阅读属性路由路由到控制器操作
In case if you're planning to have a custom action name similar to web API's.如果您打算使用类似于 Web API 的自定义操作名称。
[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有点扩展到@nkosi
So you'll be calling as所以你会打电话给
GET: https://localhost:44302/api/BXLogs/GetLAPI
获取:https://localhost:44302/api/BXLogs/GetLAPI
Notice that请注意
Actions are inaccessible via conventional routes defined by UseEndpoints, UseMvc, or UseMvcWithDefaultRoute in Startup.Configure.
无法通过 Startup.Configure 中的 UseEndpoints、UseMvc 或 UseMvcWithDefaultRoute 定义的常规路由访问操作。
So you cannot use UseMvc routes with API所以你不能在 API 中使用 UseMvc 路由
From: https://docs.microsoft.com/en-US/aspnet/core/web-api/?view=aspnetcore-3.0来自: https : //docs.microsoft.com/en-US/aspnet/core/web-api/?view=aspnetcore-3.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.