3

私はasp.coreで新しいですので、私は{id}/visits{id}/visitに有効なルートを作成するにはどうすればよいですか?

私のコードへの有効なルートを作ってみる:

[Produces("application/json")] 
[Route("/Users")] 
public class UserController 
{ 
    [HttpGet] 
    [Route("{id}/visits")] 
    public async Task<IActionResult> GetUser([FromRoute] long id) 
    { 
     throw new NotImplementedException() 
    } 
} 

しかし、ルート{id}生成方法と同じで:

// GET: /Users/5 
[HttpGet("{id}")] 
public async Task<IActionResult> GetUser([FromRoute] long id) 
{ 
    return Ok(user); 
} 

ルートを作る方法/Users/5/visits nethod?
GetUserのどのパラメータを追加すればよいですか?

答えて

4

名前は異なる方法やルートの競合を避けるために、制約を使用します。

[Produces("application/json")] 
[RoutePrefix("Users")] // different attribute here and not starting /slash 
public class UserController 
{ 
    // Gets a specific user 
    [HttpGet] 
    [Route("{id:long}")] // Matches GET Users/5 
    public async Task<IActionResult> GetUser([FromRoute] long id) 
    { 
     // do what needs to be done 
    } 

    // Gets all visits from a specific user 
    [HttpGet] 
    [Route("{id:long}/visits")] // Matches GET Users/5/visits 
    public async Task<IActionResult> GetUserVisits([FromRoute] long id) // method name different 
    { 
     // do what needs to be done 
    } 
} 
関連する問題