.Net 核心 MVC 控制器,可选参数路由规则打破空值

问题描述

在 .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)
{
            ....
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...