C# 使用asp.net路由url

C# 使用asp.net路由url,c#,asp.net-mvc,asp.net-mvc-routing,C#,Asp.net Mvc,Asp.net Mvc Routing,我是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")] [Api

我是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();
    }
}
但我无法调用该方法。如何使用此url调用
CreateCode
?我可以更改方法,但不能更改url

url正在使用:

https://localhost:44349/api/QRCode

调用方法
GetQRCodeItems

使用当前代码

[路由(“api/QRCode”)]
是控制器中所有操作的基本路由

方法的
Route
属性中的值连接到控制器的基本路由

因此,对于
[路由(“CreateCode/{Version}/{PrintPPI}/{CellSize}”)]
(注意删除了前导斜杠字符),完整路由是:

api/QRCode/CreateCode/{Version}/{PrintPPI}/{CellSize}

https://localhost:44349/api/QRCode/CreateCode/1/300/2

更改代码以匹配URL

只需将您的路线下降到:
[路由(“创建代码”)]

这是因为实际的url路由结束于
../CreateCode
,而没有查询字符串。
后面的参数将从查询字符串中提取

额外的

如何正确组合路线

应用于以/don't get开头的操作的路由模板 与应用于控制器的路由模板相结合。这个例子 匹配一组类似于默认路由的URL路径


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

谢谢您的回答。我尝试过此操作,但出现错误
值“CreateCode”无效。
@A.pissica您是否尝试过删除joure
Route
中的/before CreateCode属性?所以:
[Route(“CreateCode/{Version}/{PrintPPI}/{CellSize}”)]
是的,我看到了“朋友”的答案,但结果是一样的。谢谢你的回答。我的问题是,我需要将uri与
CreateCode?Version=1&PrintPPI=300&CellSize=2一起使用
。与
[Route(“CreateCode”)]
一起使用它工作得非常好!非常感谢。
https://localhost:44349/api/QRCode
[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();
    }   
}