【问题标题】: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


【解决方案1】:

使用基于属性的路由,可以这样做。

[HttpGet("{id:int}")]
public async Task<IActionResult> GetUserById(int id) {}

[HttpGet("{id:int}/profile")]
public async Task<IActionResult> GetUserProfileById(int id) {}

有关路由的更多信息可以在此链接中找到。

https://docs.asp.net/en/latest/fundamentals/routing.html

【讨论】:

    【解决方案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 示例。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 1970-01-01
      • 2020-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多