2016-11-08 72 views
0

我想知道如何在點網核心中指定路由。例如,我有一個get方法,它獲得1個參數(id),並返回用戶。此方法可通過此鏈接(api/user/1)獲得。 所以,問題是如何使這個鏈接的方法 - 「API /用戶/ 1 /配置文件」,以便它將獲得ID並返回與此ID相關的內容。是否需要製作2個get方法,或者將它們分開並指定路徑?ASP點網核心

+0

請將您的標題更改爲對問題更具說明性的內容 –

回答

2

使用基於屬性的路由,可以這樣做。

[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

0

如果你還沒有從改變默認路由:

app.UseMvc(routes => 
{ 
    routes.MapRoute(
     name: "default", 
     template: "{controller=Home}/{action=Index}/{id?}"); 
}); 

您可以創建一個用戶控制器的東西,如:

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示例。