我需要一些幫助來弄清楚如何在此設定中按名稱獲取物體:
// get: /api/v1/users/
[HttpGet]
public virtual async Task<IActionResult> Get()
{
var items = await service.GetAll();
if (!items.Any()) return NotFound();
return Ok(items);
}
// get: /api/v1/users/{id}
[HttpGet("{id}")]
public virtual async Task<IActionResult> Get(int id)
{
var item = await service.Get(id);
if (item == null) return NotFound();
return Ok(item);
}
// get: /api/v1/users/?name={name}
[HttpGet("{name}")]
public virtual async Task<IActionResult> Get([FromQuery]string name)
{
var item = await service.GetByUserId(name);
if (item == null) return NotFound();
return Ok(item);
}
Get()并且有效,Get(int id)但是當我呼叫https://xxx/api/v1/users/?name=foo該Get()方法并回傳所有物體時。如何按名稱獲取物體?
uj5u.com熱心網友回復:
路由中間件將傳入請求的 URL 映射到適當的操作方法。在此程序中,中間件僅使用 URL 段值來識別合適的操作方法。因此,即使您?name=""在查詢字串中指定了值,中間件也會始終將您的請求映射到默認Get()方法。
您可以通過修改 URL 路徑輕松解決此問題(我相信,您知道如何實作它)。但是,如果您打算保持 URL 路徑不變,那么稍微調整一下您的代碼,它就會起作用。
// get: /api/v1/users/
// get: /api/v1/users/?name={name}
[HttpGet]
public virtual async Task<IActionResult> Get([FromQuery]string name)
{
if(name is null) return GetAllUsers();
return return GetByUserName(name);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/488174.html
標籤:asp.net-mvc 休息 asp.net 核心
上一篇:使用api從卡匯款到貝寶賬戶
