繁体   English   中英

.Net core MVC Controller 与可选参数路由规则打破 null 值

[英].Net core MVC Controller with optional parameter routing rules breaking with null values

在 .net 核心应用程序上接线,启动设置如下所示

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
       
    

有一个自定义 controller 和 controller 的定义如下

[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)
    { 
        
    }
         

此路由规则似乎适用于页面大小的所有非 null 值,如下面的 https://localhost:44320/invoice/20210209-0035/20/11/overview/ 也正在工作并获取如下参数

        identifier=20210209-0035
        itemsCount=20
        pagesize=11     

但是当尝试使用 null 的 pagesize 值进行调用时,应用程序返回 404 Page Not found
这个 url: 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)
{
            ....
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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