路由 url 与 asp.net

Routing url with asp.net

我是 asp.net 的新手。我想使用 asp.net 创建一个网络服务。我使用 this tutorial.

创建了一个项目

我有这些 class :

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();
    }
}

我尝试用这个 url 访问 CreateCode :

https://localhost:44349/api/CreateCode?Version=1&PrintPPI=300&CellSize=2

但是我无法调用该方法。如何使用此 url 调用 CreateCode ?我可以更改方法,但不能更改 url.

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 - Combining routes 关于如何正确组合路由

Route templates applied to an action that begin with a / don't get combined with route templates applied to the controller. This example matches a set of URL paths similar to the default route

[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();
    }   
}

在方法上定义的路由附加到在 class 级别定义的路由,因此它将是:https://localhost:44349/api/QRCode/CreateCode?Version=1&PrintPPI=300&CellSize=2.