【问题标题】:ASP dot net coreASP点网核心
【发布时间】:2017-03-22 01:31:17
【问题描述】:
我想知道如何在 dot net core 中指定路由。例如,我有一个 get 方法,它获取 1 个参数(id),并返回用户。此方法可通过此链接 (api/user/1) 获得。
所以,问题是如何为这个链接创建一个方法——“api/user/1/profile”,以便它获取 ID 并返回与这个 ID 相关的内容。是否有必要制作 2 个 get 方法,或者只是将它们分开并指定路由?
【问题讨论】:
标签:
asp.net
routes
asp.net-core
asp.net-core-webapi
get-method
【解决方案2】:
如果您没有从以下位置更改默认路由:
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
你可以创建一个 User 控制器,比如:
public async Task<IActionResult> Profile(int? id)
{
if (id == null)
{
// Get the id
}
var profile = await _context.Profile
.SingleOrDefaultAsync(m => m.Id == id);
if (profile == null)
{
return NotFound();
}
return View(profile);
}
然后它会被映射到“/User/Profile/{id}”
显然,您可以随心所欲地获取配置文件的数据,我只是使用了一个 EFCore 示例。