问题描述
在 .net 核心应用程序上运行和启动设置如下
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",template: "{controller=Home}/{action=Index}/{id?}");
});
[Route("Purchase")]
public class InvoiceController : Controller
{
[HttpGet("{identifier}/{itemsCount}/overview")]
public async Task<IActionResult> GetInvoiceOverview(string identifier,int itemsCount)
{
A call to url like this //https://localhost:44320/invoice/20210209-0035/20/overview/
is working correctly and getting param values as
identifier=20210209-0035
itemsCount=20
}
}
我正在尝试向此列表添加一个可选参数,现在新的操作定义是这样的
[HttpGet("{identifier}/{itemsCount}/{pagesize?}/overview")]
public async Task<IActionResult> GetInvoiceOverview(string identifier,int itemsCount,string pagesize=null)
{
}
此规则似乎适用于 pagesize 的所有非空值,如下所示 https://localhost:44320/invoice/20210209-0035/20/11/overview/ 也在工作并获取如下参数
identifier=20210209-0035
itemsCount=20
pagesize=11
但是当尝试使用 pagesize 的空值进行调用时,应用程序返回 404 Page Not found
这个网址:https://localhost:44320/invoice/20210209-0035/20/overview/ => 404
这背后的原因可能是什么?
解决方法
你可以尝试使用2个属性路由
[HttpGet("~/invoice/{identifier}/{itemsCount}/overview")]
[HttpGet("~/invoice/{identifier}/{itemsCount}/{pagesize:int}/overview")] //:int is optional
public async Task<IActionResult> GetInvoiceOverview(string identifier,int itemsCount,int? pagesize)
{
....
}