[英]Routing url with asp.net
我是asp.net的新手。 我想使用asp.net創建一個Web服務。 我使用本教程創建了一個項目。
我有這些課:
public class QRCodeItem
{
[Key]
public Byte Version { get; set; }
public int PrintPPI { get; set; }
public int CellSize { get; set; }
}
[Route("api/QRCode")]
[ApiController]
public class QRCodeController : ControllerBase
{
[HttpGet]
[Route("/CreateCode/{Version}/{PrintPPI}/{CellSize}")]
public async Task<ActionResult<IEnumerable<QRCodeItem>>> CreateCode(Byte Version = 1, int PrintPPI = 300, int CellSize = 5)
{
return await _context.QRCodeItems.ToListAsync();
}
[HttpGet]
public async Task<ActionResult<IEnumerable<QRCodeItem>>> GetQRCodeItems()
{
return await _context.QRCodeItems.ToListAsync();
}
}
我嘗試使用以下網址訪問CreateCode
:
https://localhost:44349/api/CreateCode?Version=1&PrintPPI=300&CellSize=2
但是我無法調用該方法。 如何使用此URL調用CreateCode
? 我可以更改方法,但不能更改URL。
網址正在使用:
https://localhost:44349/api/QRCode
調用方法GetQRCodeItems
。
使用當前代碼
[Route("api/QRCode")]
是控制器中所有動作的基本路徑。
方法的Route
屬性中的值將聯接到控制器的基本路由上。
因此,對於[Route("CreateCode/{Version}/{PrintPPI}/{CellSize}")]
(請注意刪除前導斜杠字符),完整路由為:
api/QRCode/CreateCode/{Version}/{PrintPPI}/{CellSize}
https://localhost:44349/api/QRCode/CreateCode/1/300/2
更改代碼以匹配URL
只需將您的路線下拉至: [Route("CreateCode")]
之所以有效,是因為實際的URL路由以.../CreateCode
結尾,而沒有查詢字符串。 ?
之后的參數 將從查詢字符串中提取。
額外
Microsoft Docs-合並路由以了解如何正確合並路由
應用於/開頭的動作的路由模板與應用於控制器的路由模板不合並 。 此示例匹配與默認路由類似的一組URL路徑
[Route("Home")]
public class HomeController : Controller
{
[Route("")] // Combines to define the route template "Home"
[Route("Index")] // Combines to define the route template "Home/Index"
[Route("/")] // Doesn't combine, defines the route template ""
public IActionResult Index()
{
ViewData["Message"] = "Home index";
var url = Url.Action("Index", "Home");
ViewData["Message"] = "Home index" + "var url = Url.Action; = " + url;
return View();
}
[Route("About")] // Combines to define the route template "Home/About"
public IActionResult About()
{
return View();
}
}
在該方法上定義的路由將追加到在類級別定義的路由,因此它將為: https://localhost:44349/api/QRCode/CreateCode?Version=1&PrintPPI=300&CellSize=2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.