我正在嘗試將我的 UI 專案和 WebAPI 專案合二為一以使其更易于維護,但是我遇到了如下路由錯誤:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:64182/api/v1/business?id=101'.",
"MessageDetail": "No type was found that matches the controller named 'api'."
}
我在方法上添加了屬性路由以使其作業,但它僅適用于以下 url:
MVC 動作:
[HttpGet, Route("api/v1/business/{id:int}")]
public IHttpActionResult Get([FromUri]int? id)
{
....
}
http://localhost:64182/api/v1/business/101
預期的 url 簽名不能更改,它仍應使用查詢引數:
http://localhost:64182/api/v1/business?id=101
在 Route 屬性中,我不能添加問號,因為這是不允許的。
該系統已經被許多用戶使用,不幸的是我無法更改簽名,否則這會破壞他們的系統。
我怎樣才能讓它作業或者我可以使用什么路由模板來包含查詢引數?
uj5u.com熱心網友回復:
我認為 [FromUri] 屬性已被棄用。嘗試使用 [FromRoute]。此外,我將從控制器類構建我的路由。
以下是 http://localhost:64182/api/v1/business/101
[Route("api/v1/[controller]")]
[ApiController]
public class Business : ControllerBase
{
[HttpGet("/{id:int}")]
public async Task<ActionResult<YourBusinessDto>> Get([FromRoute] int id)
{
//Your code to get your business dto here.
}
}
以下為 http://localhost:64182/api/v1/business?id=101
[Route("api/v1/[controller]")]
[ApiController]
public class Business : ControllerBase
{
[HttpGet]
public async Task<ActionResult<YourBusinessDto>> Get([FromQuery] int id)
{
//Your code to get your business dto here.
}
}
uj5u.com熱心網友回復:
在我們的訂單集合中,每個訂單都有一個唯一的識別符號。我們可以去集合,通過“id”來請求。典型的 RESTful 最佳實踐,這可以通過其路由檢索,例如“api/orders/1”
//api/orders/1
[HttpGet("api/orders/{id}")]
public string test1([FromRoute]int id)
{
return "test1";
}
此屬性將指示 ASP.NET Core 框架將此操作視為 HTTP GET 動詞的處理程式并處理路由。我們提供端點模板作為屬性引數。此模板用作框架將用于匹配傳入請求的路由。在這個模板中,{id}?? 的值對應路由部分作為“id”引數。FromRoute 屬性告訴框架在路由 (URL) 中查找“id”值并將其作為 id 引數提供。
此外,我們可以輕松撰寫它以使用 FromQuery 屬性。然后,這會指示框架使用“識別符號”名稱和相應的整數值來預測查詢字串。然后將該值作為 id 引數傳遞給操作。其他一切都是一樣的。
然而,最常見的方法是前面提到的 FromRoute 用法——其中識別符號是 URI 的一部分
//api/orders?id=1
[HttpGet("api/v1")]
public string test2([FromQuery]int id)
{
return "test2";
}
另外,更多的屬性用法可以參考這篇詳細的文章,可能對你有幫助:
https://www.dotnetcurry.com/aspnet/1390/aspnet-core-web-api-attributes
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/346047.html
標籤:C# asp.net-mvc asp.net核心 asp.net-web-api 路线
