繁体   English   中英

用asp.net路由URL

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM